import os
import re
import requests
from html.parser import HTMLParser

BUILDBOT_URL = "https://builder.blender.org/"
BUILDBOT_DOWNLOAD_URL = BUILDBOT_URL + "download/"


class BuildbotHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.official_builds = []

    def handle_starttag(self, tag, attrs):
        tag_lower = tag.lower()
        if tag_lower == 'a':
            for attr in attrs:
                if attr[0].lower() == 'href':
                    href = attr[1]
                    if href.startswith("/download/"):
                        self.official_builds.append(os.path.basename(href))
        elif tag_lower == 'table':
            classes = ()
            for attr in attrs:
                if attr[0].lower() == 'class':
                    classes = attr[1].lower().split()
            if 'table-striped' in classes:
                pass

    def handle_endtag(self, tag):
        pass

    def handle_data(self, data):
        pass


def _getBuildbotPlatformRegex(platform, bitness):
    platform_lower = platform.lower()
    if platform_lower in ("linux", "lin"):
        if bitness.startswith("64"):
            return re.compile(".*linux-glibc[0-9]+-x86_64.*")
        elif bitness.startswith("32"):
            return re.compile(".*linux-glibc[0-9]+-i686.*")
    elif platform_lower in ("win32"):
        if bitness.startswith("64"):
            return re.compile(".*win64.*")
        elif bitness.startswith("32"):
            return re.compile(".*win32.*")
    else:
        # TOGO(sergey): Needs implementation
        pass
    return None


def buildbotGetLatetsVersion(platform, bitness):
    """
    Get latest Blender version URL from buildbot website.

    Returns None if something is wrong.
    """
    # Get content of the page.
    r = requests.get(BUILDBOT_DOWNLOAD_URL)
    if r.status_code != requests.codes.ok:
        return None
    # Parse the page.
    parser = BuildbotHTMLParser()
    parser.feed(r.text)
    official_builds = parser.official_builds
    # Get build which corresponds to requested platform.
    regex = _getBuildbotPlatformRegex(platform, bitness)
    if not regex:
        return None
    for build in official_builds:
        if regex.match(build):
            return BUILDBOT_DOWNLOAD_URL + build
    return None
