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 = 'modjp_budget_index'

    start_urls = [
        'https://www.mod.go.jp/j/budget/yosan_gaiyo/index.html'
    ]

    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):
        tab_area = response.xpath("//div[@class='content-section']/div[@class='tabs-section']/section")
        for tab in tab_area:
            table_lines = tab.xpath(".//li")
            for line in table_lines:
                content = "".join(line.xpath(".//text()").extract())
                pdf_name = line.xpath("./a/text()").extract()[0].replace('\n', '').replace(" ", "").replace("\t", "")
                pdf_url = line.xpath("./a/@href").extract()[0]
                pdf_url = build_url(response.url, [], pdf_url)
                page_item = WebsiteSpiderItem()
                page_item['es_attachment'] = [pdf_url]
                page_item['es_urltitle'] = pdf_name
                page_item['es_urlcontent'] = content
                try:
                    time_str = line.xpath("./text()").extract()[0].strip()
                    page_item['es_urltime'] = get_time_stamp(time_str)
                    if page_item['es_urltime'] == 0:
                        page_item['es_urltime'] = int(time.time() * 1000)
                except:
                    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.mod.go.jp/'
                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'] = 'JPN'
                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
