"""Module contains functionality that parser main page for Apple vulnerabilities."""

import urllib.request
from cve_connector.vendor_cve.implementation.parsers.general_and_format_parsers\
    .html_parser import HtmlParser
from cve_connector.vendor_cve.implementation.utilities.utility_functions \
    import string_to_date


class AppleMainPageParser(HtmlParser):
    """
    Class providing functionality for parsing Apple main page.
    """
    def __init__(self, url, from_date=None, to_date=None):
        super().__init__(url, from_date, to_date)
        self.load_content()
        self.date_format = '%d %b %Y'  # 29 Mar 2018

    def get_content_from_ulr(self):
        """
        Gets and returns content from URL.

        :return: content
        """
        response = urllib.request.urlopen(self.url)
        if response.getcode() != 200:
            raise ConnectionError('Unable to load ', self.url)
        content = response.read()
        response.close()
        return content

    def parse(self):
        """
        Provides parsing functionality.

        :return: None
        """
        content = self.data.xpath(
            './/div[@id="sections"]'
            '//div[h2[contains(text(), "Apple security updates")]]//table/tbody')
        if not content:
            raise ValueError('Format of parsed Apple website has changed.')

        table_rows = content[0].xpath('./tr')
        for row in table_rows:
            table_data = row.xpath('./td')
            if table_data:
                url, parsed_date = self.parse_table_row_data(table_data)
                if url is not None and parsed_date is not None and \
                        self.from_date <= parsed_date <= self.to_date:
                    self.entities.append(url)

    def parse_table_row_data(self, data):
        """
        Parses row of table.

        :param data: table
        :return: tuple - url, published date
        """
        if data[0].xpath('./a/@href'):
            url = data[0].xpath('./a/@href')[0]
        else:
            url = None
        pub_date = string_to_date(data[2].xpath('./text()')[0], self.date_format)
        return url, pub_date
