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

import os
import ConfigParser
import re

from clcommon.cpapi.cpapiexceptions import NotSupported
from clcommon.cpapi.plugins.universal import _dblogin_cplogin_pairs


__cpname__ = 'InterWorx'

PARSE_URI_PATTERN = re.compile(r'(.+)://(.+):(.+)@.*')


def detect():
    return os.path.isfile('/usr/local/interworx/iworx.ini')

IWORX_INI = '/usr/local/interworx/iworx.ini'


def db_access(_conf_path=IWORX_INI):
    access = dict()
    data_config = ConfigParser.ConfigParser()
    data_config.read(_conf_path)

    mysql_uri = data_config.get(section='mysql', option='rootdsn').strip('\"')
    parse_result = PARSE_URI_PATTERN.search(mysql_uri)
    (db, login, passwd) = (None, None, None)
    if parse_result:
        (db, login, passwd) = parse_result.group(1, 2, 3)
    access['login'] = login
    access['pass'] = passwd
    access['host'] = data_config.get(section='mysql', option='default_server').strip('\"')
    access['db'] = db
    return access


def cpusers():
    raise NotSupported('Getting all users registered in the Control Panel is not currently supported. '
                       'Is under development.')


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
