
# -*- coding: utf-8 -*-
from setuphelpers import *
from setupdevhelpers import *
import glob
import re



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

  
    url_base = "https://www.roboform.com/download"
    response = requests.get(url_base,allow_redirects=True, proxies=proxies)
    # Extract the correct div using bs_find_all
    divs = bs_find_all(response.text, "div","class","action", proxies=proxies)
    exe_file = None
    for div in divs:
        if exe_file:
            break
        links = div.find_all('a', href=True)
        for link in links:
            if link['href'].endswith('.exe'):
                href = link['href']
                exe_file = href
                download_url = exe_file
                latest_bin = exe_file.split('/')[-1]
                version = latest_bin.split("-")[1].replace("v","")
                break
    # Find the div with class "info-text" to get the version
    #info_text_divs = bs_find_all(response.text,"div", "class","info-text", proxies=proxies)
    #version = None
    #version_pattern = re.compile(r'RoboForm for Windows MSI v(\d+\.\d+\.\d+)')
    #for div in info_text_divs:
        #h3 = div.find('h3')
        #if h3:
            #match = version_pattern.search(h3.text)
            #if match:
                #version = match.group(1)
                #break


    # Downloading latest binaries
    print("Download URL is: %s" % download_url)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, latest_bin, proxies=proxies)
        package_updated = True
    else:
        print("Binary is present: %s" % latest_bin)


    # Deleting outdated binaries
    for f in glob.glob('*.exe'):
        if f != latest_bin:
            remove_file(f)

      
    version = get_version_from_binary(latest_bin)
    # Mettre à jour le package
    control.set_software_version(version)
    control.save_control_to_wapt()    
        

