from urllib import request
from html.parser import HTMLParser

NAME = "HD-Jiggly"
COOKIE = 'cookie.txt'


class parseLinks(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.data = []
        self.flag_tbody = False
        self.flag_span = False
        self.flag_a = False
        self.flag_td = False
        self.flag_a2 = False
        self.link = ''
        self.title = ''
        self.name = ''

    def handle_starttag(self, tag, attrs):
        if tag == 'tbody':
            for name, value in attrs:
                if name == 'id' and value.find("normalthread_") == 0:
                    self.flag_tbody = True

        if tag == 'span'and self.flag_tbody == True:
            for name, value in attrs:
                if name == 'id' and value.find("thread_") == 0:
                    self.flag_span = True
        if tag == 'a' and self.flag_span == True:
            for name, value in attrs:
                if name == 'href' and value.find("thread-") == 0:
                    self.link = "http://174.127.195.166/forum/" + value
                    self.flag_a = True

        if tag == 'td'and self.flag_tbody == True:
            for name, value in attrs:
                if name == 'class' and value.find("author") == 0:
                    self.flag_td = True
        if tag == 'a' and self.flag_td == True:
            self.flag_a2 = True

    def handle_data(self, data):
        if self.flag_span == True and self.flag_a == True:
            self.title = data
            self.flag_span = False
            self.flag_a = False
        if self.flag_td == True and self.flag_a2 == True:
            self.name = data
            if(self.name == NAME):
                self.data.append(self.title)
                self.data.append(self.link)
            self.flag_td = False
            self.flag_a2 = False
            self.flag_tbody = False


class crawlerSISID():
    def __init__(self, index):
        url = "http://174.127.195.166/forum/forum-463-" + str(index) + ".html"
        self.parse = parseLinks()
        self.request = request.urlopen(url)
        self.parse.feed(self.request.read().decode('gbk'))

    def crawlerData(self):
        self.request.close()
        return self.parse.data


# print(crawlerSISID(1).crawlerData())
