#!/usr/bin/python
# -*- coding: utf-8 -*-

__cpname__ = 'DirectAdmin'


def detect():
    return os.path.isfile('/usr/local/directadmin/directadmin') or \
           os.path.isfile('/usr/local/directadmin/custombuild/build')


import os
import glob
import re

from clcommon.clconfpars import load as loadconfig
from clcommon.cpapi.cpapiexceptions import NoDBAccessData, CpApiTypeError
from clcommon.cpapi.plugins.universal import _dblogin_cplogin_pairs
from clcommon import ClPwd


DA_DB_CONF = '/usr/local/directadmin/conf/mysql.conf'
DA_USERS_PATH = '/usr/local/directadmin/data/users'
USER_CONF = 'user.conf'
RESELLERS_LIST = '/usr/local/directadmin/data/admin/reseller.list'
USER_PATTERN = re.compile(r'.+/(.+)/%s' % re.escape(USER_CONF))
USERCONF_PARAM_MAP = {
    'dns': 'domain',
    'package': 'package',
    'mail': 'email',
    'locale': 'language',
    'cplogin': 'name',
    'reseller': 'reseller'
}


def db_access(_conf_path=DA_DB_CONF):
    access = dict()
    try:
        login_data = loadconfig(_conf_path)

        access['login'] = login_data['user']
        access['pass'] = login_data['passwd']
    except IOError, err:
        raise NoDBAccessData('Can not open file with data to database access; ' + str(err))
    except KeyError:
        raise NoDBAccessData('Can not get database access data from file %s' % (_conf_path,))
    return access


def cpusers(_path=DA_USERS_PATH):
    match_list = [USER_PATTERN.match(path) for path in glob.glob(os.path.join(_path, '*', USER_CONF))]
    users_list = [match.group(1) for match in match_list if match]
    return tuple(users_list)


def resellers(_resellers_path=RESELLERS_LIST):
    stream = open(_resellers_path)
    resellers_list = map(str.strip, stream.readlines())
    stream.close()
    return tuple(resellers_list)


def dblogin_cplogin_pairs(cplogin_lst=None, with_system_users=False):
    access = db_access()
    data = _dblogin_cplogin_pairs(cplogin_lst=cplogin_lst, access=access)
    return data


def cpinfo(cpuser=None, keyls=('cplogin', 'package', 'mail', 'reseller', 'dns', 'locale'),
           _path=DA_USERS_PATH):
    returned = list()
    if isinstance(cpuser, (str, unicode)):
        cpusers_list = [cpuser]
    elif isinstance(cpuser, (list, tuple)):
        cpusers_list = tuple(cpuser)
    elif cpuser is None:
        match_list = [USER_PATTERN.match(path) for path in glob.iglob(os.path.join(_path, '*', USER_CONF))]
        cpusers_list = [match.group(1) for match in match_list if match]
    else:
        raise CpApiTypeError(funcname='cpinfo', supportettypes='str|unicode|list|tuple',
                             received_type=type(cpuser).__name__)

    # generate user reseller map
    user_reseller_map = dict()
    reseller_list_stream = open(RESELLERS_LIST)
    for reseller_login in reseller_list_stream:
        reseller_cpuser_list = open(os.path.join(os.path.join(_path, reseller_login.strip(), 'users.list')))
        user_reseller_map.update(dict([(user_name, reseller_login) for user_name in reseller_cpuser_list
                                       if user_name in cpusers_list]))
        reseller_cpuser_list.close()

    for cpuser in cpusers_list:
        cpuser_data = loadconfig(os.path.join(_path, cpuser, 'user.conf'))
        cpuser_data['reseller'] = user_reseller_map.get(cpuser)  # insert reseller login
        cpuser_data_lst = tuple([cpuser_data.get(USERCONF_PARAM_MAP.get(key)) for key in keyls])
        if cpuser_data_lst not in returned:
            returned.append(cpuser_data_lst)
    return returned

def homedirs(_sysusers=None, _path=DA_USERS_PATH):
    """
    Detects and returns list of folders contained the home dirs of users of the DirectAdmin

    :param str|None _sysusers: for testing
    :param str|None _path: for testing
    :return: list of folders, which are parent of home dirs of users of the panel
    """

    homedirs = []

    clpwd = ClPwd()
    users_dict = clpwd.get_user_dict()

    # for testing only
    if isinstance(_sysusers, (list, tuple)):
        class pw(object):
            def __init__(self, name, dir):
                self.pw_name = name
                self.pw_dir = dir

        users_dict = {}
        for (name,dir) in _sysusers:
            users_dict[name] = pw(name, dir)

    for user_name in users_dict:
        conf_file = _path + '/' + user_name + '/user.conf'
        if os.path.exists(conf_file):
            homedir = os.path.dirname(users_dict[user_name].pw_dir)
            if homedir not in homedirs:
                homedirs.append(homedir)

    return homedirs
