import time
import pymysql
from lib.database.db_setting import DBSetting


class DBManager:
    def __init__(self, mode):
        self.conn = None
        self.curs = None
        self.db_setting = DBSetting(mode)
        # super().__init__()

    def connect(self):
        self.conn = pymysql.connect(
            host=self.db_setting.host, port=self.db_setting.port,
            user=self.db_setting.user, password=self.db_setting.password,
            db=self.db_setting.db, charset=self.db_setting.charset)

    def select(self, sql):
        self.execute_sql(sql, [])
        self.conn.close()
        rows = self.curs.fetchall()
        return rows

    def insert(self, sql, params):
        self.execute_sql(sql, params)
        self.conn.commit()
        self.conn.close()

    def update(self, sql, params):
        self.execute_sql(sql, params)
        self.conn.commit()
        self.conn.close()

    def delete(self, sql, params):
        self.execute_sql(sql, params)
        self.conn.commit()
        self.conn.close()

    def execute_sql(self, sql, params):
        self.connect()
        self.curs = self.conn.cursor(pymysql.cursors.DictCursor)
        # print(type(sql))
        # print(sql)
        # print(type(params))
        # print(params)
        self.curs.execute(sql, params)

    @staticmethod
    def get_datetime_now():
        return time.strftime('%Y-%m-%d %H:%M:%S')