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

try:
    import MySQLdb
except ImportError:
    MySQLdb = None

from clcommon.cpapi.cpapiexceptions import NotSupported, NoPackage
from clcommon import ClPwd


PSA_SHADOW_PATH = "/etc/psa/.psa.shadow"


__cpname__ = 'Plesk'


def detect():
    return os.path.isfile('/usr/local/psa/version')


def db_access(_pass_path=PSA_SHADOW_PATH):
    access = dict()
    access['login'] = 'admin'
    f = open(_pass_path)
    access['pass'] = f.read().strip()
    f.close()
    return access


def cpusers(_accsess=None, _dbname='psa'):
    if not MySQLdb:
        raise NoPackage('Can not connect to database; MySQL-python package not installed.')
    access = _accsess or db_access()
    dbhost = access.get('host', 'localhost')
    dblogin = access['login']
    dbpass = access['pass']
    db = MySQLdb.connect(host=dbhost, user=dblogin, passwd=dbpass, db=_dbname)
    cursor = db.cursor()
    sql = r"SELECT login FROM sys_users"
    cursor.execute(sql)
    cpusers_lst = [fetched_one[0] for fetched_one in cursor.fetchall()]
    db.close()
    return cpusers_lst


def dblogin_cplogin_pairs(cplogin_lst=None, with_system_users=False):
    raise NotSupported('Getting binding credentials in the database to the user name in the system is not currently '
                       'supported. Is under development.')

def homedirs(_sysusers=None, _cpusers=None):
    """
    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 = []

    if _cpusers is None:
        try:
            results = cpusers()
        except NoPackage:
            results = None
    else:
        results = _cpusers

    users = []
    if results is not None:
        users = [line.encode('utf8') for line in results]

    # Plesk assumes MIN_UID as 10000
    clpwd = ClPwd(10000)
    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:
        if len(users) and user_name not in users:
            continue
        homedir = os.path.dirname(users_dict[user_name].pw_dir)
        if homedir not in homedirs:
            homedirs.append(homedir)

    return homedirs

