#VERSION: 1.01
# AUTHORS: nindogo
# CONTRIBUTORS: Diego de las Heras (ngosang@hotmail.es)

try:
    # python3
    from html.parser import HTMLParser
except ImportError:
    # python2
    from HTMLParser import HTMLParser

# qBt
from novaprinter import prettyPrinter
from helpers import retrieve_url


class eztv(object):
    name = "EZTV"
    url = 'https://eztv.ag'
    supported_categories = {'all': 'all', 'tv': 'tv'}

    class MyHtmlParser(HTMLParser):
        A, TD, TR, TABLE = ('a', 'td', 'tr', 'table')

        """ Sub-class for parsing results """
        def __init__(self, url):
            HTMLParser.__init__(self)
            self.url = url

            self.in_table_row = False
            self.current_item = {}

        def handle_starttag(self, tag, attrs):
            params = dict(attrs)

            if (params.get('class') == 'forum_header_border'
                    and params.get('name') == 'hover'):
                self.in_table_row = True
                self.current_item = {}
                self.current_item['leech'] = -1
                self.current_item['engine_url'] = self.url

            if (tag == self.A
                    and self.in_table_row and params.get('class') == 'magnet'):
                self.current_item['link'] = params.get('href')

            if (tag == self.A
                    and self.in_table_row and params.get('class') == 'epinfo'):
                self.current_item['desc_link'] = self.url + params.get('href')
                self.current_item['name'] = params.get('title').split(' (')[0]

            if (tag == self.TD
                    and params.get('class') == 'forum_thread_post_end'
                    and params.get('align') == 'center'):
                prettyPrinter(self.current_item)
                self.in_table_row = False

        def handle_data(self, data):
            data = data.replace(',', '')
            if (self.in_table_row
                    and (data.endswith('MB') or data.endswith('GB') or data.endswith('KB'))):
                self.current_item['size'] = data

            if self.in_table_row and (data.isalnum() or data == '-'):
                if data.isalnum():
                    self.current_item['seeds'] = int(data)
                else:
                    self.current_item['seeds'] = 0

        def handle_endtag(self, tag):
            if self.in_table_row and tag == self.TR:
                self.in_table_row = False

    def search(self, what, cat='all'):
        query = self.url + '/search/' + what.replace('%20', '-')
        eztv_html = retrieve_url(query)

        eztv_parser = self.MyHtmlParser(self.url)
        eztv_parser.feed(eztv_html)
        eztv_parser.close()


if __name__ == '__main__':
    eztv_se = eztv()
    eztv_se.search('Acre', 'all')
