# -*-  coding: UTF-8 -*-
#!/usr/bin/env python3
'__autor__'== 'serkus'
import os, sys, json
from urllib import request
from utils.package import search
#import xml
import xml.etree.ElementTree as ET
#Проверяем пользователь ROOT или нет
def is_root():
	return os.geteuid() == 0
	
#Читаем Файл посторочно
def read_configs(filename):
	param = {}
	if os.path.exists(filename):
		with open(filename) as f:
			for line in f: 
				print(line)
	else:
		print("Path is not Found")

#получаем список оверлеев
def enable_overlays():
	path='/etc/portage/repos.conf/'
	
def get_list_overlays():
	overlays =[]
	OverlayList={}
	url = "https://qa-reports.gentoo.org/output/repos/repositories.xml"   #    "https://api.gentoo.org/overlays/repositories.xml"
	if(os.path.exists("./overlays.json")):
		with open("./overlays.json", 'a') as fn:
			try:
				OverlayList = json.load(fn.read())
			except Exception as e:
				print(e)
	else:
		overlays = []
		response = request.urlopen(url)
		overlay = {}
		includes =[]
		catalogOverls ={}
		root = ET.fromstring(response.read())
		#print(root.attrib)
		name = ""
		#print(root.tag)
		description = ""
		homepage = ""
		feed =""
		for d, dirs, files in os.walk('/var/db/repos'):
			if(d == "/var/db/repos"):
				inc = dirs
			else:
				break
		
		for child in root.findall('repo'):
			name = child.find('name').text
			try:
				description = child.find('description').text
			except AttributeError: 
				description = "У overlay нет описания"
			try:
				homepage = child.find('homepage').text
			except AttributeError:
				homepage = "У overlay нет домашней странички"
			
			try:
				feed = child.find('feed').text
			except AttributeError:
				feed = "У overlay нет ссылки и на дерево"
				
			overlay =dict(name=name, description=description, homepage=homepage, feed=feed)
            
			if name in inc:
				includes.append(overlay)

			overlays.append(overlay)

			if " for " in description:
				if description.split(" for ")[1].split(" ")[0] not in catalogOverls:
					catalogOverls[description.split(" for ")[1].split(" ")[0]] =[]
				catalogOverls[description.split(" for ")[1].split(" ")[0]].append(overlay)
			elif "Personal overlay" in description or "personal overlay" in description:
				if "Personal " not in catalogOverls:
					catalogOverls["Personal"] =[]
				catalogOverls["Personal"].append(overlay)
			else:
				if "othes" not in catalogOverls:
					catalogOverls["othes"] =[]
				catalogOverls["othes"].append(overlay)
			
				
			#print(str(overlays))s
			#print(len(overlays))
		with open('./overlays.json', 'a') as  f:
			f.write(json.dumps({"repositories": dict(all=overlays, include=includes, categores=catalogOverls)}))
			#f.close()
		OverlayList = dict(all=overlays, include=includes,categores=catalogOverls)
		#except Exception as e:
		#	print(e)
			#return 1
	return OverlayList  # dict(all=overlays, include=includes)


def xml_element_to_dict(elem):
	"Convert XML Element to a simple dict"
	inner = dict(elem.attrib)
	children = list(map(xml_element_to_dict, list(elem)))
	text = elem.text and elem.text.strip()
	if text:
		inner['@text'] = text
	if children:
		inner['@children'] = children
	return {elem.tag: inner}

def xml2json(xmldata):
	pass
	#doc = ET.parse(xmldata)
	#root = root = ET.fromstring(xmldata)

def write_config(port=8000, Lang='ru', theme="default"):
	
	conf = dict(PORT=port, Lang=Lang, THEME=theme)
	with open('./config.json', 'w') as f:
	    json.dump(conf, f)
	return conf

def read_config():
	with open('./config.json', 'r') as f:
	    conf = json.load(f)
	return conf

def load_config():
	conf = {}
	if not os.path.exists("./config.json"):
		write_config()
	else:
		conf = read_config()
	return conf

#SORT IN  INTALL PAKAGES
#''
def sort_install_pkg():
	#pkg =scan_config_portage()
	INSTALL = {}
	pkg_name =""
	path = '/var/db/pkg/'
	for d, dirs, files in os.walk(path):
		for f in files:
			try:
				#ver=int(f.replace('.ebuild', '').split('-')[-1][0])
				for pn in f.replace('.ebuild', '').split('-')[:-1]:
					pkg_name = pkg_name + pn + "-"
			#except TypeError:
			#	for pn in f.replace('.ebuild', '').split('-')[:-2]:
			#		pkg_name = pkg_name + pn + "-"
			except Exception as e:
					print(e)
			#print(e)
			#print(pkg_name)
			if pkg_name not in INSTALL:
				INSTALL[d.replace(path, "").split('/')[0]] =[]
			INSTALL[d.replace(path,"").split('/')[0]].append(dict(name=pkg_name[:-1], ver=f.replace(pkg_name, "")))
			"""
			else:
				INSTALL[d.replace(path,
					"").split('/')[0]].append(dict(name=pkg_name[:-1],ver=f.replace(pkg_name, "")
                
                if d.replace(path, "").split('/')[0] not in INSTALL:
                    INSTALL[d.replace(path, "").split('/')[0]] =[]
                    INSTALL[d.replace(path, "").split('/')[0]].append(f.replace(".ebuild", "") )
                INSTALL[d.replace(path,
                    "").split('/')[0]].append(f.replace(".ebuild", "")) #dict(name=pkg_name[:-1],ver=f.replace(pkg_name, "")
                """

    #print(str(len(INSTALL)))
    #return json.dumps({'install_pkgs':INSTALL})
	return  INSTALL

def scan_config_portage():
    dirs_root =["/var/db/repos", "/usr/portage"]
    config = {}
    i = 0
    dr = {}
    data = {}
    pf={}
    for dir_root in dirs_root:
        for d, dirs, files in os.walk(dir_root):
            print(str(d))
            i=i+1
            for fl in files:
                with open(d + "/" + fl) as f:
                    pf[str(d.split('/')[-1]) +  "/"+ fl]= f.read().split('\n')
                    str(d.split('/')[-1])
    #print(dr)
    #config = {'portage': pf}
    #print("config:\t" + str(config))
    return config
