import json
import os
def _decode_list(data):
    rv = []
    for item in data:
        if isinstance(item, str):
            item = item.encode('utf-8')
        elif isinstance(item, list):
            item = _decode_list(item)
        elif isinstance(item, dict):
            item = _decode_dict(item)
        rv.append(item)
    return rv

def _decode_dict(data):
    rv = {}
    for key, value in list(data.items()):
        if isinstance(key, str):
            key = key.encode('utf-8')
        if isinstance(value, str):
            value = value.encode('utf-8')
        elif isinstance(value, list):
            value = _decode_list(value)
        elif isinstance(value, dict):
            value = _decode_dict(value)
        rv[key] = value
    return rv


'''Python 3 compatible codes '''

def readjson(datafile):
    with open(datafile,'r') as data_file:
        try:
            data = json.load(data_file)
        except ValueError as e:
            data={}
    return data



def readjsonval(datafile,field):
    with open(datafile,'r') as data_file:
        try:
            data = json.load(data_file)
        except ValueError as e:
            data={}
    return data.get(field)



def writejson(db,filename):
    with open(filename, 'w') as fp:
        json.dump(db,fp)



def get_ssl_domains_local():
    with open('/etc/ssldomains') as sfile:
        lines=sfile.read().splitlines()
    ssldom={}
    for line in lines:
        x=line.split(":")
        domain=x[0]
        ip=x[1].strip()
        ssldom[domain] =[domain,ip]
    return ssldom

def ipv6_get_user():
    cmd='/usr/sbin/whmapi1 ipv6_range_list --output=json'
    datas=os.popen(cmd).read()
    dresult={}
    result={}
    try:
        dresult=json.loads(datas)
    except Exception as e:
        print((str(e)))
        pass
    for item in dresult['data']['range']:
        if item['enabled']==1:
            ipv6=item['CIDR'].split('/')[0]
            for user in item['range_users']:
                result[user]=ipv6
    return(result)
    #print(result)
    #print(dresult['data']['range'])




def get_vhost_data():
    userdata_file="/etc/userdatadomains.json"
    if os.path.exists(userdata_file):
        userdata_json=readjson(userdata_file)
        ssldomains=get_ssl_domains_local()
        ipv6data=ipv6_get_user()
        userdata={}
        for domain in userdata_json:
            domainuser=userdata_json[domain][0].strip()
            dopmaintype=userdata_json[domain][2].strip()
            domainreal=userdata_json[domain][3].strip()
            domaindocroot=userdata_json[domain][4].strip()
            domainip=userdata_json[domain][5].split(':')[0].strip()
            if  domainuser not  in ipv6data.keys():
                ipv6='::'
                ipvstatus='0'
            elif bool(ipv6data) and bool(ipv6data[domainuser]):
                ipv6=ipv6data[domainuser]
                ipvstatus='1'
            else:
                ipv6='::'
                ipvstatus='0'
            userdata[domain]=[domain,domainuser,dopmaintype,domainreal,domaindocroot,domainip,ipvstatus,ipv6]
    else:
        userdata={}
    return userdata 



