from io import StringIO

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


# qgis releases
def get_latest_qgis_version() -> str:
    """
    Return latest available QGIS version.
    """
    url = "https://qgis.org/resources/roadmap/"
    r = requests.get(
        url,
        headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
        },
    )
    # dont use lxml because of possible segfault on windows
    df = pd.read_html(StringIO(r.text), flavor="bs4")[0]
    df["delta"] = (pd.Timestamp.today() - pd.to_datetime(df["Date"])).dt.total_seconds()
    df = df[df["delta"] >= 0]
    latest_version = df.loc[df["delta"].argmin(), "Latest"]

    return latest_version


def get_openlog_last_version() -> tuple:
    """
    Return latest openlog version and minimal required QGIS version
    """
    url = "https://plugins.qgis.org/plugins/openlog/#plugin-versions"
    r = requests.get(
        url,
        headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
        },
    )
    df = pd.read_html(StringIO(r.text), flavor="bs4")[0]
    df = df.sort_values("Version", ascending=False)
    openlog_version, qgis_min_version = df.iloc[0, 0], df.iloc[0, 2]
    return openlog_version, qgis_min_version


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
