import re, pymysql.cursors


class MySQL:
    __conn__ = None
    __curr__ = None

    def __init__(self, **kwargs):
        if kwargs:
            self.connect(**kwargs)

    def connect(self, host=None, port=0, user=None, password='', database=None, charset='', cursor='Dict'):
        if self.__conn__:
            raise Exception('连接已存在 | Connection already exists.')
        match cursor:
            case 'Index':
                cursorClass = pymysql.cursors.Cursor
            case 'Dict':
                cursorClass = pymysql.cursors.DictCursor
            case _:
                cursorClass = pymysql.cursors.DictCursor
        self.__conn__ = pymysql.connect(
            host=host, port=port,
            user=user, password=password,
            database=database, charset=charset,
            autocommit=True,
            connect_timeout=10,
            cursorclass=cursorClass,
            client_flag=pymysql.constants.CLIENT.MULTI_STATEMENTS
        )
        self.__curr__ = self.__conn__.cursor()
        return self

    def execute(self, *args):
        if self.__curr__ is None:
            raise Exception('连接不存在 | Connection does not exist.')
        self.__curr__.execute(*args)
        return self

    def count(self):
        if self.__curr__ is None:
            raise Exception('连接不存在 | Connection does not exist.')
        return self.__curr__.rowcount

    def fetchall(self):
        if self.__curr__ is None:
            raise Exception('连接不存在 | Connection does not exist.')
        return self.__curr__.fetchall()

    def fetchone(self):
        if self.__curr__ is None:
            raise Exception('连接不存在 | Connection does not exist.')
        return self.__curr__.fetchone()

    def close(self):
        if self.__curr__ or self.__conn__:
            self.__curr__.close()
            self.__conn__.close()
            self.__curr__ = None
            self.__conn__ = None
        return True


if __name__ == '__main__':
    # Example.
    connConfig = {
        "host": "127.0.0.1", "port": 3306, "user": "root", "password": "root", "database": "db", "charset": "utf8",
    }
    sqlConnect = MySQL(**connConfig, cursor='Dict')
    sqlConnect.execute('''
    CREATE TABLE `user` (
        `uid`              int(11)     NOT NULL AUTO_INCREMENT,
        `username`         char(20)    DEFAULT NULL,
        `email`            varchar(64) DEFAULT NULL,
        `phone`            char(11)    DEFAULT NULL,
        `password`         char(32)    DEFAULT NULL,
        PRIMARY KEY (`uid`),
        UNIQUE KEY `username` (`username`),
        UNIQUE KEY `email` (`email`),
        UNIQUE KEY `phone` (`phone`)
    )
    ENGINE=MyISAM AUTO_INCREMENT=10000 DEFAULT CHARSET=utf8;
    ''')
    print('RowCounts:', sqlConnect.count(), 'SqlResult:', sqlConnect.fetchall())
    sqlConnect.execute('''
    INSERT INTO user (username,email,phone,password) VALUES ("刘德华","10000@example.com","13512310000","0123456789abcdef0123456789abcdef");
    ''')
    print('RowCounts:', sqlConnect.count(), 'SqlResult:', sqlConnect.fetchall())
    sqlConnect.execute('''
    INSERT INTO user (username,email,phone,password) VALUES ("周润发","10002@example.com","13512310002","0123456789abcdef0123456789abcdef");
    ''')
    print('RowCounts:', sqlConnect.count(), 'SqlResult:', sqlConnect.fetchall())
    sqlConnect.execute('''
    SELECT * FROM user WHERE uid LIKE "1%";
    ''')
    print('RowCounts:', sqlConnect.count(), 'SqlResult:', sqlConnect.fetchall())
    sqlConnect.execute('''
    DROP TABLE user;
        ''')
    print('RowCounts:', sqlConnect.count(), 'SqlResult:', sqlConnect.fetchall())
    sqlConnect.close()
