import json
import logging
import time

import scrapy
import validators
from scrapy.loader import ItemLoader

from CustomWebsite.items import WebsiteSpiderItem
from CustomWebsite.utils.date_utils import get_time_stamp
from CustomWebsite.utils.http_utils import build_url


class WebsiteSpider(scrapy.Spider):
    name = 'mofa_tw'

    start_urls = [
        'https://www.mofa.gov.tw/News.aspx?n=139&sms=142'
    ]

    def __init__(self, params=None, *args, **kwargs):
        super(WebsiteSpider, self).__init__(*args, **kwargs)
        json_params = json.loads(params)
        if 'job_id' in json_params:
            self.job_id = json_params['job_id']

    def parse(self, response, **kwargs):
        lines = response.xpath("//table//tr")
        for line in lines:
            try:
                content = "".join(line.xpath(".//a/text()").extract())
                pdf_name = line.xpath(".//a/text()").extract()[0].replace('\n', '').replace(" ", "")
                pdf_url = line.xpath(".//a/@href").extract()[0]
                page_item = WebsiteSpiderItem()
                page_item['es_attachment'] = [pdf_url]
                page_item['es_urltitle'] = pdf_name
                page_item['es_urlcontent'] = content
                page_item['es_urltime'] = int(time.time() * 1000)
                page_item['es_urlname'] = pdf_url
                page_item['es_lasttime'] = page_item['es_urltime']
                page_item['es_attention'] = page_item['es_urltitle']
                page_item['es_sitename'] = '“中华民国外交部”'
                page_item['es_srcname'] = 'https://www.mofa.gov.tw/'
                page_item['es_loadtime'] = str(int(time.time() * 1000))
                page_item['es_carriertype'] = 'article'
                page_item['es_catalog'] = '政府机构'
                page_item['es_catalog2'] = 'pdf'
                page_item['es_collection'] = '白皮书'
                page_item['es_lang'] = 'TWN'
                page_item['es_doclength'] = len(page_item['es_urlcontent'])
                # logging.info((page_item['es_attachment'], page_item['es_attention'], page_item['es_urltime']))
                response.request.meta['CUSTOM_FILTER_KEY'] = 'URL_Filter:Custom:' + self.name
                response.request.meta['CUSTOM_FILTER_VAL'] = page_item['es_urlname']
                yield page_item
            except:
                continue
