# coding: utf-8

from base import  *
from sys_services import *

def get_mysql_info():
    """
    获取以安装数据库信息
    """
    data = {}
    try:
        path = get_server_path('mysql')
        name = re.search('([MySQL|MariaDB-]+\d+\.\d+)', path).groups()[0]
        myconf = ReadFile(GetConfigValue('setup_path') + '/mysql/' + name + '/my.ini')
        rep = "port\s*=\s*([0-9]+)"

        data['port'] = int(re.search(rep, myconf).groups()[0])
        data['name'] = name
        data['path'] = GetConfigValue('setup_path') + '/mysql/' + data['name']
        data['version'] = re.search("(\d*\.\d*)", name).groups()[0]
        return data
    except :
        data['path'] = ''
        return data

def CheckMyCnf():
    pass

def get_database_character(db_name):
    """
    获取mysql字符集
    @db_name 数据库名称
    return str 字符集
    """
    try:
        db_obj = get_mysql_obj(db_name)
        tmp = db_obj.query("show create database `%s`" % db_name.strip())
        c_type = str(re.findall(r"SET\s+([\w\d-]+)\s",tmp[0][1])[0])
        c_types = ['utf8','utf-8','gbk','big5','utf8mb4']
        if not c_type.lower() in c_types: return 'utf8'
        return c_type
    except:
        return 'utf8'

# 取mysql数据库对象
def get_mysql_obj(db_name):
    is_cloud_db = False
    if db_name:
        db_find = M('databases').where("name=?" ,db_name).find()
        if db_find['sid']:
            return get_mysql_obj_by_sid(db_find['sid'])
        is_cloud_db = db_find['db_type'] in ['1',1]


    if is_cloud_db:
        import db_mysql
        db_obj = db_mysql.panelMysql()
        conn_config = json.loads(db_find['conn_config'])
        try:
            db_obj = db_obj.set_host(conn_config['db_host'],conn_config['db_port'],conn_config['db_name'],conn_config['db_user'],conn_config['db_password'])
        except Exception as e:
            raise PanelError(GetMySQLError(e))
    else:
        import panelMysql
        db_obj = panelMysql.panelMysql()
    return db_obj

# 取mysql数据库对像 By sid
def get_mysql_obj_by_sid(sid = 0,conn_config = None):
    if type(sid) == str:
        try:
            sid = int(sid)
        except :sid = 0

    if sid:
        if not conn_config: conn_config = M('database_servers').where("id=?" ,sid).find()
        import db_mysql
        db_obj = db_mysql.panelMysql()

        try:
            db_obj = db_obj.set_host(conn_config['db_host'],conn_config['db_port'],None,conn_config['db_user'],conn_config['db_password'])
        except Exception as e:
            raise PanelError(GetMySQLError(e))
    else:

        import panelMysql
        db_obj = panelMysql.panelMysql()
    return db_obj

def GetMySQLError(e):
    res = ''
    if e.args[0] == 1045:
        res = '数据库用户名或密码错误!'
    if e.args[0] == 1049:
        res = '数据库不存在!'
    if e.args[0] == 1044:
        res = '没有指定数据库的访问权限，或指定数据库不存在!'
    if e.args[0] == 1062:
        res = '数据库已存在!'
    if e.args[0] == 1146:
        res = '数据表不存在!'
    if e.args[0] == 2003:
        res = '数据库服务器连接失败!'
    if e.args[0] == 1142:
        res = '指定用户权限不足!'
    if res:
        res = res + "<pre>" + str(e) + "</pre>"
    else:
        res = str(e)
    return res

def get_database_codestr(codeing):
    wheres = {
        'utf8': 'utf8_general_ci',
        'utf8mb4': 'utf8mb4_general_ci',
        'gbk': 'gbk_chinese_ci',
        'big5': 'big5_chinese_ci'
    }
    return wheres[codeing]


def get_database_size(name=None):
    """
    @获取数据库大小
    """
    data = {}
    try:
        mysql_obj = get_mysql_obj(name)
        tables = mysql_obj.query("select table_schema, (sum(DATA_LENGTH)+sum(INDEX_LENGTH)) as data from information_schema.TABLES group by table_schema")
        if type(tables) == list:
            for x in tables:
                if len(x) < 2:continue
                if x[1] == None:continue
                data[x[0]] = int(x[1])
    except: return data
    return data

def get_database_size_by_name(name):
    """
    @获取数据库大小
    """
    data = 0
    try:
        mysql_obj = get_mysql_obj(name)

        tables = mysql_obj.query("select table_schema, (sum(DATA_LENGTH)+sum(INDEX_LENGTH)) as data from information_schema.TABLES WHERE table_schema='{}' group by table_schema".format(name))
        data = tables[0][1]
        if not data: data = 0
    except: return data
    return data

def get_database_size_by_id(id):
    """
    @获取数据库大小
    """
    data = 0
    name = M('databases').where('id=?',id).getField('name')

    mysql_obj = get_mysql_obj(name)

    try:
        tables = mysql_obj.query("select table_schema, (sum(DATA_LENGTH)+sum(INDEX_LENGTH)) as data from information_schema.TABLES WHERE table_schema='{}' group by table_schema".format(name))
        print(tables)
        data = tables[0][1]
        if not data: data = 0
    except :pass
    return data