import requests
import re
from packaging import version
import subprocess

from logger import critical, info, error

errorMessage = subprocess.run(['python3', '/app/MsRewards-Reborn/modules/Tools/generate_error.py'], check=False, stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE).stderr.decode("utf-8")

versionPattern = "This version of ChromeDriver only supports Chrome version ([0-9]+)"

try:
    versionN = re.search(versionPattern, errorMessage)[1]
except Exception as e:
    critical("Can't get version number from error")
    error(e)
    info("error message")
    info(errorMessage)
    exit(0)

info(f"Needed version : '{versionN}'")

downloadUrl = "http://mirror.cs.uchicago.edu/google-chrome/pool/main/g/google-chrome-stable/"
r = requests.get(downloadUrl)

content = r.text

exactVersionList = re.findall(f"(google-chrome-stable_({versionN}.[0-9.]+)[^<^>^\"]+)", content)

try:
    best = exactVersionList[0]
except Exception as e:
    critical("No version matches required version")
    error(e)
    exit(0)

for i in exactVersionList:
    if version.parse(i[1]) > version.parse(best[1]):
        best = i

chromeDebURL = f"http://mirror.cs.uchicago.edu/google-chrome/pool/main/g/google-chrome-stable/{best[0]}"
info(f"chrome deb URL : {chromeDebURL}")
info("downloading chrome")

subprocess.call(['wget', "-O", "/tmp/chrome.deb", chromeDebURL])
info("Chrome deb downloaded. Installing chrome")

subprocess.call(["dpkg", "-i", "/tmp/chrome.deb"])
info("Chrome installed")