# coding=utf-8
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2022 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT
#
import asyncio
import collections
import json
import os
import re
import shlex
import ssl
import sys
import subprocess
from concurrent.futures.process import ProcessPoolExecutor
import configparser
from aiohttp import web
from clcommon.ui_config import UIConfig
from clcommon.cpapi import is_panel_feature_supported

from constants import *

def run_cmd_pw_runner(pw, cmd):
    return run_cmd(cmd)


async def run_cmd_pw(pw, cmd):
    """Run cmd async"""
    loop = asyncio.get_event_loop()
    executor = ProcessPoolExecutor(max_workers=1)
    result = await loop.run_in_executor(
        executor,
        run_cmd_pw_runner, pw, cmd)
    return result

def drop_admin(uid, gid):
    """Drop privileges to user"""
    os.setgroups([])
    os.setgid(gid)
    os.setuid(uid)


def run_cmd(cmd):
    """Run subprocess"""
    if isinstance(cmd, str):
        cmd = shlex.split(cmd)
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    return proc.returncode, stdout.decode(), stderr.decode()


DICT_PARAM = r'^(.*)\[(.*)\]$'
def parse_params(params):
    """Parse request params array"""
    result = collections.defaultdict(dict)
    for key in params.keys():
        res = re.match(DICT_PARAM, key)
        if res:
            result[res[1]][res[2]] = params.get(key)
        else:
            result[key] = params.get(key)

    return result


def get_service_port():
    return 9000

def get_ssl_context():
    return None


async def get_user_data(user_data):
    """User data"""
    return {
               "userName": "root",
               "userType": "admin",
               "lang": "en",
               "assetsUri": "/admin/lvemanager",
               "baseUri": "/admin/lvemanager",
               "defaultDomain": "nopanel.cloudlinux.com"
           }

def is_admin(username):
    """Check if given user is an admin"""
    return True

def is_reseller(username):
    """Check if given user is a reseller"""
    return False

def get_admins():
    """Get list of all admins"""
    return ['root']

def get_resellers():
    """Get list of all resellers"""
    return []

def get_user_type(username):
    """Get type of given user (admin, reseller, user)"""
    return TYPE_ADMIN

def get_user_plugins():
    """Get available plugins for end-user"""
    return [{'title': 'CloudLinux Manager','ui_option': None}]
