import { BrowserWindow } from 'electron';
import {
  open,
  Protocol,
  SimConnectDataType,
  SimConnectPeriod,
  SimConnectConstants,
  readLatLonAlt,
  RecvSimObjectData
} from 'node-simconnect';
import { DataDefiniion } from './DataDefinition';
import { DefinitionID, EventID, RequestID } from './enums';

export class SimconnectClient {
  private requestsMap: Map<number, Function>;
  private isPaused: Boolean;
  private onGround: Boolean;
  private onRunway: Boolean;
  private window: BrowserWindow;

  constructor() {
    this.requestsMap = new Map();
    this.isPaused = true;
    this.onGround = true;
    this.onRunway = false;

  }

  async open(win: BrowserWindow) {
    const { recvOpen, handle } = await open('My SimConnect client', Protocol.KittyHawk);
    console.log('Connected to', recvOpen);
    this.subscribeToSystemEvent(handle);
    this.addDataDefinitions(handle);
    this.window = win;
    handle.on('simObjectData', this.objectDataHandler.bind(this));

  }

  objectDataHandler(objectData: RecvSimObjectData) {
    const { requestID, data } = objectData;
    if (this.requestsMap.has(requestID)) {
      const fn: Function = this.requestsMap.get(requestID);
      fn(data, this.window);
    }
  }

  subscribeToSystemEvent(handle) {
    handle.subscribeToSystemEvent(EventID.PAUSE, 'Pause');

    handle.on('event', function(recvEvent) {
      switch (recvEvent.clientEventId) {
        case EventID.PAUSE:
          console.log(recvEvent.data === 1 ? 'Sim paused' : 'Sim unpaused');
          this.isPaused = recvEvent.data === 1;
          break;
      }
    }.bind(this));
  }

  addDataDefinitions(handle) {
    const onGroundDef = new DataDefiniion(
      DefinitionID.ON_GROUND, 
      RequestID.ON_GROUND,
      SimConnectPeriod.SECOND,
      data => {
        const onGround = data.readInt32() === 1;
        console.log('On Groud :>> ', onGround);
        this.onGround = onGround;
      }
    );
    const onRunwayDef = new DataDefiniion(
      DefinitionID.ON_RUNWAY, 
      RequestID.ON_RUNWAY,
      SimConnectPeriod.SECOND,
      (data, window) => {
        const isOnRunway = data.readInt32() === 1;
        console.log('On Runway :>> ', isOnRunway);
        this.onRunway = isOnRunway;
        window.send('data_on_runway', this.onRunway);
      }
    );
    const liveDef = new DataDefiniion(
      DefinitionID.LIVE_DATA, 
      RequestID.LIVE_DATA,
      SimConnectPeriod.SECOND,
      data => {
        console.log('this.isPaused :>> ', this.isPaused);
        if (!this.isPaused) {
          const timestamp = new Date().getTime();
          const { latitude, longitude, altitude } = readLatLonAlt(data);
          const airspeed = data.readInt32();
          const verticalSpeed = data.readInt32();
          const heading = data.readInt32();
          console.log("position", `${latitude} ${longitude} ${altitude}`,
            "airspeed", airspeed,
            "vertical speed", verticalSpeed,
            "heading", heading,
            // "landing lights", recvSimObjectData.data.readInt32(),
            // "logo lights", recvSimObjectData.data.readInt32(),
            // "taxi lights", recvSimObjectData.data.readInt32(),
            // "wing lights", recvSimObjectData.data.readInt32(),
            // "nav lights", recvSimObjectData.data.readInt32(),
            // "beacon lights", recvSimObjectData.data.readInt32()
          );
        }
      }
    );
    const aircraftDef = new DataDefiniion(
      DefinitionID.AIRCRAFT_DATA, 
      RequestID.AIRCRAFT_DATA,
      SimConnectPeriod.ONCE,
      data => {
        console.log('===================================');
        console.log(`Type: "${data.readStringV()}"`);
        console.log(`Title: "${data.readStringV()}"`);
        console.log(`ATC ID: "${data.readString32()}"`);
        console.log('===================================');
      }
    );
    onGroundDef.add(['SIM ON GROUND', 'bool', SimConnectDataType.INT32, 0, SimConnectConstants.UNUSED]);
    onRunwayDef.add(['ON ANY RUNWAY', 'bool', SimConnectDataType.INT32, 0, SimConnectConstants.UNUSED])
    liveDef.add(['STRUCT LATLONALT', null, SimConnectDataType.LATLONALT]);
    liveDef.add(['AIRSPEED INDICATED', 'knots', SimConnectDataType.INT32]);
    liveDef.add(['VERTICAL SPEED', 'Feet per second', SimConnectDataType.INT32]);
    liveDef.add(['PLANE HEADING DEGREES TRUE', 'Degrees', SimConnectDataType.INT32]);
    liveDef.add(['LIGHT LANDING', 'bool', SimConnectDataType.INT32]);
    liveDef.add(['LIGHT LOGO', 'bool', SimConnectDataType.INT32]);
    liveDef.add(['LIGHT TAXI', 'bool', SimConnectDataType.INT32]);
    liveDef.add(['LIGHT WING', 'bool', SimConnectDataType.INT32]);
    liveDef.add(['LIGHT NAV', 'bool', SimConnectDataType.INT32]);
    liveDef.add(['LIGHT BEACON', 'bool', SimConnectDataType.INT32]);
    aircraftDef.add(['CATEGORY', null, SimConnectDataType.STRINGV, 0, SimConnectConstants.UNUSED]);
    aircraftDef.add(['TITLE', null, SimConnectDataType.STRINGV, 0, SimConnectConstants.UNUSED]);
    aircraftDef.add(['ATC ID', null, SimConnectDataType.STRING32, 0, SimConnectConstants.UNUSED]);
    onGroundDef.build(handle, this.requestsMap);
    onRunwayDef.build(handle, this.requestsMap);
    liveDef.build(handle, this.requestsMap);
    // aircraftDef.build(handle, this.requestsMap);
  }

}