# -*- coding: utf-8 -*-
from setuphelpers import *
import gzip
from io import BytesIO
from setuphelpers import Version,wgets
from setupdevhelpers import *
import requests


def update_package():
    # Declaring local variables
    proxies = get_proxies_from_wapt_console()
    if not proxies:
        proxies = get_proxies()

    dict_arch = {"x64": "amd64"}
    urldepot = 'https://deb.nodesource.com/node_20.x'
    arch = dict_arch[control.architecture]
    package_name_list = ["nodejs"]

    with gzip.open(BytesIO(requests.get('%s/dists/nodistro/main/binary-%s/Packages.gz' % (urldepot,arch),proxies=proxies).content)) as f:
        data = f.read().decode('utf-8')

    list_package = listcontrol_to_dict_data(data,'\nPackage: ')
    all_dep=[]

    last_version= None
    list_deb = []
    for package_name in package_name_list :

        last_package = sorted([u for u in list_package if u['package'] == package_name], key=lambda p: (Version(p['version'].split(':',1)[-1].split('+')[0],4)), reverse=True)[0]
        if not last_version:
            last_version = last_package['version'].split(':',1)[-1].split('+')[0]

        all_dep.append(last_package)

        for s in last_package.get('depends','').split(','):
            for p in s.split('|'):
                get_all_dep_version_pacakge(list_package,p.split('(')[0].strip(),all_dep)

        for u in all_dep:
            list_deb.append(urldepot + '/' + u['filename'])

    list_all_file = []
    for f in list_deb:
        filename = f.split('/')[-1]
        list_all_file.append(filename)
        if not isfile(filename):
            wget(f,filename,proxies=proxies)

    for f in glob.glob('*.deb'):
        if not f in list_all_file:
            remove_file(f)

    control.set_software_version(str(Version(last_version,4)).split('-')[0])
    control.save_control_to_wapt()



def listcontrol_to_dict_data(data=None, first_entry=None):
    list_package = '\n' + data
    list_control=[]
    for i in list_package.split(first_entry):
        if not i.strip('\n'):
            continue
        list_control.append(first_entry.replace('\n','') + i)

    list_package = []
    for pkg in list_control:
        entry = {}
        gpg = False
        for l in pkg.split('\n'):

            if '-----BEGIN PGP PUBLIC KEY BLOCK-----' in l:
                gpg = True
                continue
            if '-----END PGP PUBLIC KEY BLOCK-----' in l:
                gpg = False
                continue
            if gpg :
                continue

            if not l:
                continue
            if (':' in l) and (not '::' in l) and (not l.startswith(' ')) :
                key = l.split(':',1)[0].strip().lower()
                value = l.split(':',1)[1].strip()
                entry[key] = value.strip('\n')
            else:
                entry[key] =  entry[key].strip('\n') + ' ' if entry[key].strip() else "" + l.strip()

        list_package.append(entry)
    return list_package

def get_all_dep_version_pacakge(list_package,package_name,all_dep):
    last_package = sorted([u for u in list_package if u['package'] == package_name], key=lambda p: (Version(p['version'].split(':',1)[-1].split('+')[0])), reverse=True)
    if last_package:
        last_package = last_package[0]
        all_dep.append(last_package)
    else:
        return
    for k in last_package.get('depends','').split('|'):
        for p in k.split(','):
            get_all_dep_version_pacakge(list_package,p.split('(')[0].strip(),all_dep)