# -*- coding: utf-8 -*-
import scrapy
import json
import time
from copy import deepcopy
from AirplaneSpiders.items import AirPlaneLiveItem


# 全球飞机实时轨迹采集--数据源：flightradar24.com #
class AirplaneLive2Spider(scrapy.Spider):
    name = 'flightradar24_airplane_live'
    allowed_domains = ['flightradar24.com']
    start_urls = [
        'https://data-live.flightradar24.com/zones/fcgi/feed.js?bounds=82.33,-84.66,-450.16,450.16&faa=1&satellite=1&mlat=1&flarm=1&adsb=1&gnd=1&air=1&vehicles=1&estimated=1&maxage=14400&gliders=1&stats=1&enc=ObcT4uk9D_AxHltTtqhJ95cHvrRvNejTPoWu2q_tZVM']

    custom_settings = {
        'PROTO_MODULE_PATH': 'AirplaneSpiders.proto.Plane_pb2',
        'PROTO_CLASS_NAME': 'FligthTrackpointInfoSets',
        'PROTO_FIELD_NAME': 'FligthTrackpointInfo',
        'PROTO_SAVE_FILE_PATH': r'/usr/local/spider_data',
        'PROTO_SAVE_FILE_NAME': r'track_data_plane_',
        'ITEM_PIPELINES': {
            'AirplaneSpiders.pipelines.ProtobufSavePipeline': 300,
            'AirplaneSpiders.pipelines.FlightIdSavePipeline': 301
        }
    }

    def __init__(self, params=None, *args, **kwargs):
        super(AirplaneLive2Spider, 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):
        try:
            live_data = json.loads(response.text)
            for key in live_data.keys():  # key为航班id
                if key == 'stats' or key == 'full_count' or key == 'version' or live_data[key][9] == '':
                    continue
                item = AirPlaneLiveItem()
                item['FlightID'] = '2#%s' % key
                item['Latitude'] = live_data[key][1]
                item['Longitude'] = live_data[key][2]
                item['LastTime'] = str(live_data[key][10]) + '000'
                if live_data[key][4] is not None:
                    item['Height'] = int(live_data[key][4]) * 0.3048  # 英尺转米
                item['model'] = live_data[key][8]
                item['Speed'] = live_data[key][5]  # 速度单位kts
                item['Angle'] = live_data[key][3]
                item['source'] = 'flightradar24'
                item['PlaneREG'] = live_data[key][9]
                item['FlightICAO'] = live_data[key][0]
                item['UpdateTime'] = str(int(time.time() * 1000))
                yield item
                # base_url = 'https://data-live.flightradar24.com/clickhandler/?version=1.5&flight='
                # yield scrapy.Request(base_url + key, callback=self.parseAirport, meta={'item': deepcopy(item)})
        except Exception as e:
            self.logger.error("来自数据源 flightradar24 的飞机实时信息解析错误，原因是：", e)

    def parse_airport(self, response):
        item = response.request.meta['item']
        data = json.loads(response.text)
        if data['airport']['origin'] is not None:
            item['origAirport'] = data['airport']['origin']['name']
        if data['airport']['destination'] is not None:
            item['destAirport'] = data['airport']['destination']['name']

        yield item
