/// <reference types="@microsoft/msfs-types/Pages/VCockpit/Core/VCockpit" />
/// <reference types="@microsoft/msfs-types/JS/dataStorage" />

import { EventBus, FSComponent, SimVarPublisher, SimVarValueType, Subject } from '@microsoft/msfs-sdk';
import { OFP } from './components/ofp/ofp';
import { TLR } from './components/tlr/tlr';

import './index.scss';

export interface NewDataEvents {
  newData: boolean;
  position: number;
}

class KH_FE_FPLAN extends BaseInstrument {
  private readonly bus = new EventBus();
  private readonly newDataPublisher = new SimVarPublisher<NewDataEvents>(
    new Map([
      ['newData', { name: 'L:KH_FE_FPLAN_NEW_DATA', type: SimVarValueType.Bool }],
      ['position', { name: 'L:KH_FE_FPLAN_BOARD', type: SimVarValueType.Number }],
    ]),
    this.bus
  );
  private contentOFP = Subject.create<string>('');
  private contentTLR = Subject.create<string>('');
  private position = Subject.create<number>(0);

  private sbID = '';

  get templateID(): string {
    return 'kh-fe-fplan';
  }

  get isInteractive() {
    return true;
  }

  constructor() {
    super();

    const config = GetStoredData('FSS_B727_EFB_CONFIG_PREFLIGHT');
    try {
      this.sbID = JSON.parse(config).simBriefId;
    } catch (e) {
      console.error('Failed loading config.', e);
    }
  }

  private getSB = async (): Promise<void> => {
    try {
      const res = await fetch(`https://www.simbrief.com/api/xml.fetcher.php?username=${this.sbID}&json=1`);
      if (res.ok) {
        try {
          const data = await res.json();

          let ofp: string = data.text.plan_html;
          ofp = ofp.replace(/href=".*?"/g, '');

          this.contentOFP.set(ofp);
          this.contentTLR.set(data.text.tlr_section);
        } catch (e) {
          console.error('JSON DECODE ERR', e);
        }
      }
    } catch (e) {
      console.error('FETCH ERR', e);
    }
  };

  private reloadSB = (): void => {
    SimVar.SetSimVarValue('L:KH_FE_FPLAN_NEW_DATA', 'bool', 1);
  };

  protected Update(): void {
    super.Update();

    this.newDataPublisher.onUpdate();
  }

  public connectedCallback(): void {
    super.connectedCallback();

    this.newDataPublisher.startPublish();
    const sub = this.bus.getSubscriber<NewDataEvents>();
    sub.on('newData').handle((flag) => {
      if (!flag) return;
      SimVar.SetSimVarValue('L:KH_FE_FPLAN_NEW_DATA', 'bool', 0);
      this.getSB();
    });
    sub.on('position').handle((position) => {
      this.position.set(position);
    });

    const url = new URL(this.getAttribute('Url') ?? '');
    const type = url.searchParams.get('type');

    FSComponent.render(
      <>
        {type === 'ofp' && <OFP content={this.contentOFP} position={this.position} reload={this.reloadSB} />}
        {type === 'tlr' && <TLR content={this.contentTLR} position={this.position} reload={this.reloadSB} />}
      </>,
      document.getElementById('root')
    );
  }
}

registerInstrument('kh-fe-fplan', KH_FE_FPLAN);
