import pandas as pd
import requests
from lxml import html
from packaging.version import Version


# qgis releases
def get_latest_qgis_version() -> str:
    """
    Return latest available QGIS version.
    """
    today = str(pd.Timestamp.today())[:10]
    dt_today = pd.to_datetime(today)
    url = "https://qgis.org/resources/roadmap/"
    r = requests.get(url, timeout=30)
    h = html.fromstring(r.content)
    table = h.xpath('//table[@class="roadmap"]')[0]
    tbody = table.find("tbody")
    versions = []
    dates = []
    # recency
    deltas = []
    for row in tbody.findall("tr"):
        version, date = [
            elt.text_content() for i, elt in enumerate(row.findall("td")) if i in [1, 4]
        ]
        dt_date = pd.to_datetime(date)
        if dt_date >= dt_today:
            continue
        version = version.replace(" ", "").replace("\n", "")
        versions.append(version)
        dates.append(date)
        deltas.append(dt_today - dt_date)
    # get latest version
    index = pd.Series(deltas).argmin()
    latest_version = versions[index]
    return latest_version


def get_openlog_last_version() -> tuple:
    """
    Return latest openlog version and minimal required QGIS version
    """
    today = str(pd.Timestamp.today())[:10]
    url = "https://plugins.qgis.org/plugins/openlog/#plugin-versions"
    r = requests.get(url, timeout=30)
    h = html.fromstring(r.content)
    table = h.find_class("table versions-list-table")[0]
    tbody = table.find("tbody")
    result = {}
    versions = []
    qgis_min_version = []
    for row in tbody.findall("tr"):
        version, qgis = [
            elt.text_content() for i, elt in enumerate(row.findall("td")) if i in [0, 2]
        ]
        version = version.replace(" ", "").replace("\n", "")
        versions.append(version)
        qgis_min_version.append(qgis)

    index = pd.Series([Version(version) for version in versions]).argmax()
    return versions[index], qgis_min_version[index]


def is_openlog_up_to_date() -> str:
    """
    Check versions and return message to display.
    If returned value is None, then nothing to display.
    """
    from qgis.core import Qgis

    from openlog.__about__ import __version__

    QGIS_VERSION = Qgis.version().split("-")[0]

    openlog_latest, required_qgis = get_openlog_last_version()
    last_qgis_version = get_latest_qgis_version()

    # qgis and openlog out of date
    if (
        Version(__version__) < Version(openlog_latest)
        and Version(QGIS_VERSION).minor < Version(last_qgis_version).minor
    ):
        s = f"""
            <p align='left'>QGIS install is {QGIS_VERSION}, out of date.<br>
            OpenLog install is {__version__}, out of date.<br>
            Please update QGIS to the latest version at www.qgis.org/download/ then update OpenLog to the latest version via the plugin manager.</p>
            """
        return s
    # qgis up to date, openlog out of date
    elif (
        Version(__version__) < Version(openlog_latest)
        and Version(QGIS_VERSION).minor >= Version(last_qgis_version).minor
    ):
        s = f"""
            <p align='left'>QGIS install is {QGIS_VERSION}, up to date.<br>
            OpenLog install is {__version__}, out of date.<br>
            Please update OpenLog to the latest version via the plugin manager.</p>
            """
        return s
    # qgis out of date, openlog up to date
    elif (
        Version(__version__) >= Version(openlog_latest)
        and Version(QGIS_VERSION).minor < Version(last_qgis_version).minor
    ):
        s = f"""
            <p align='left'>QGIS install is {QGIS_VERSION}, out of date.<br>
            OpenLog install is {__version__}, up to date.<br>
            Please update QGIS to the latest version at www.qgis.org/download/</p>
            """
        return s
    else:
        return None
