# -*- coding: utf-8 -*-
import json
import redis
import scrapy
from scrapy_splash import SplashRequest
from AirplaneSpiders.items import AirPlaneLiveItem


# 高敏飞机历史轨迹下载
class SensitiveAirplaneLiveSpider(scrapy.Spider):
    name = 'radarbox_airplane_live_sensitive'
    allowed_domains = ['rb24.com', 'radarbox.com']
    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.HistoryTrackSavePipeline': 300
        },
        'DOWNLOAD_DELAY': 3
    }

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

    def start_requests(self):
        self.redis_client = redis.Redis(host=self.settings['REDIS_HOST'], port=int(self.settings['REDIS_PORT']),
                                        password=self.settings['REDIS_PWD'])
        regs = self.redis_client.smembers('AirplaneSpiders:sensitiveReg')
        self.redis_client.close()
        for reg in regs:
            yield SplashRequest(url='https://www.radarbox.com/data/registration/%s' % reg.decode(),
                                callback=self.fid_parse)
            # yield SeleniumRequest(url='https://www.radarbox.com/data/registration/%s'%reg.decode(), callback= self.fid_parse)

    def fid_parse(self, response):
        try:
            if response.text is None or len(response.text) == 0:
                return
            fids = response.xpath('//tbody/tr/@id').getall()
            for fid in fids:
                if fid.find('_') < 0:
                    continue
                fid = fid.split('_')[0]
                yield scrapy.Request('https://www.radarbox.com/data/get-replay?fid=%s' % fid,
                                     callback=self.live_data_parse)
        except Exception as error:
            print('解析航班id出错,原因是：', error)

    def live_data_parse(self, response):
        try:
            rsp = json.loads(response.text)
            if 'trails' not in rsp:
                return
            if 'flight' not in rsp:
                return
            base_data = rsp['flight']
            live_data = rsp['trails']
            item = AirPlaneLiveItem()

            item['FlightID'] = '1#%s' % str(base_data['fid'])
            if 'fnia' in base_data and base_data['fnia'] is not None:
                item['FlightIATA'] = base_data['fnia']
            if 'act' in base_data and base_data['act'] is not None:
                item['model'] = base_data['act']
            if 'acr' in base_data and base_data['acr'] is not None:
                item['PlaneREG'] = base_data['acr']
            if 'aporgic' in base_data and base_data['aporgic'] is not None:
                item['origAirport'] = base_data['aporgic']
            if 'apdstic' in base_data and base_data['apdstic'] is not None:
                item['destAirport'] = base_data['apdstic']
            if 'cs' in base_data and base_data['cs'] is not None:
                item['FlightICAO'] = base_data['cs']
            item['source'] = 'radarbox'

            for key in live_data.keys():
                temp = item.copy()
                temp['LastTime'] = key
                temp['Latitude'] = live_data[key][0]
                temp['Longitude'] = live_data[key][1]
                height_str = live_data[key][2]
                if isinstance(height_str, str) and len(height_str) == 0:
                    temp['Height'] = 0
                else:
                    temp['Height'] = int(height_str) * 0.3048
                temp['Angle'] = live_data[key][3]
                temp['Speed'] = live_data[key][4]
                temp['UpdateTime'] = key
                yield temp
        except Exception as e:
            self.logger.error('飞机实时信息解析错误，原因是：', e)
