# -*- coding: utf-8 -*-
import base64
from setuphelpers import *
from setupdevhelpers import *
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name

    url = "https://filezilla-project.org/download.php?show_all=1"
    dict_arch_name = {"x64": "_win64-setup.exe", "x86": "_win32-setup.exe"}

    content = requests.get(url, proxies=proxies, headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0", 
        'Referer': 'https://filezilla-project.org/download.php'
    }).text

    contentwrapper = bs_find(content, 'div', 'id', 'contentwrapper')
    iv = base64.b64decode(contentwrapper.get('v1'))
    key = base64.b64decode(contentwrapper.get('v2'))
    # algo = base64.b64decode(contentwrapper.get('v3')).decode("utf-8")
    ciphertext = base64.b64decode(contentwrapper.get_text())

    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    decryptor = cipher.decryptor()
    decrypted = decryptor.update(ciphertext) + decryptor.finalize()
    padding_length = decrypted[-1]
    plaintext = decrypted[:-padding_length].decode('utf-8')

    # Getting latest version from official sources
    print(f"URL used is: {url}")
    for bs_search in bs_find_all(plaintext, "a", "rel", "nofollow"):
        if dict_arch_name[control.architecture] in bs_search.get_text():
            latest_bin = bs_search.get_text()
            latest_bin_extension = latest_bin.rsplit('.', 1)[-1]
            version = latest_bin.split("_")[1]
            download_url = bs_search["href"]
            break

    # Downloading latest binaries
    print(f"Latest {app_name} version is: {version}")
    print(f"Download URL is: {download_url}")
    if not isfile(latest_bin):
        print(f"Downloading: {latest_bin}")
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print(f"Binary is present: {latest_bin}")

    # Changing version of the package
    if Version(version) > Version(control.get_software_version()):
        print(f"Software version updated (from: {control.get_software_version()} to: {Version(version)})")
        package_updated = True
    else:
        print(f"Software version up-to-date ({Version(version)})")

    for f in glob.glob(f'*.{latest_bin_extension}'):
        if f != latest_bin:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated
