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


# 全球飞机实时轨迹采集--数据源：planeradar.ru #
class AirplaneLive3Spider(scrapy.Spider):
    name = 'planeradar_airplane_live'
    allowed_domains = ['planeradar.ru']

    start_urls = [r'http://planeradar.ru/VirtualRadar/-.~DT.F-BrdUp%20%20Rt']
    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(AirplaneLive3Spider, 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:
            res_data = json.loads(response.text)
            for data in res_data['acList']:
                item = AirPlaneLiveItem()
                item['FlightID'] = '3#%s' % data['Id']
                # item['FlightIATA'] = data['']
                if 'Lat' in data and data['Lat'] is not None:
                    item['Latitude'] = data['Lat']
                if 'Long' in data and data['Long'] is not None:
                    item['Longitude'] = data['Long']
                if 'PosTime' in data and data['PosTime']:
                    item['LastTime'] = data['PosTime']
                else:
                    item['LastTime'] = res_data['stm']
                if 'Alt' in data and data['Alt'] is not None:
                    item['Height'] = int(data['Alt']) * 0.3048
                if 'Type' in data and data['Type'] is not None:
                    item['model'] = data['Type']
                if 'Spd' in data and data['Spd'] is not None:
                    item['Speed'] = data['Spd']
                if 'Trak' in data and data['Trak'] is not None:
                    item['Angle'] = data['Trak']
                item['source'] = 'planeradar.ru'
                if 'Reg' in data and data['Reg'] is not None:
                    item['PlaneREG'] = data['Reg']
                if 'From' in data and data['From'] is not None:
                    item['origAirport'] = data['From']
                if 'To' in data and data['To'] is not None:
                    item['destAirport'] = data['To']
                # item['FlightICAO'] = data['']
                # item['vs'] = data['']
                item['UpdateTime'] = str(int(time.time() * 1000))
                yield item
        except Exception as e:
            self.logger.error("来自数据源 planeradar.ru 的飞机实时信息解析错误，原因是：", e)
