import {
  ComponentProps,
  ComputedSubject,
  DisplayComponent,
  FSComponent,
  NodeReference,
  Subscribable,
  VNode,
} from '@microsoft/msfs-sdk';

import './controls.scss';

interface ControlsProps extends ComponentProps {
  containerRef: NodeReference<HTMLDivElement>;
  reload: () => void;
  position: Subscribable<number>;
  page: number;
}

export class Controls extends DisplayComponent<ControlsProps> {
  private cycleRef = FSComponent.createRef<HTMLDivElement>();
  private toTopRef = FSComponent.createRef<HTMLDivElement>();
  private reloadRef = FSComponent.createRef<HTMLDivElement>();
  private switchPosRef = FSComponent.createRef<HTMLDivElement>();
  private buttonName = ComputedSubject.create<number, string>(0, (val) => {
    if (val === 1) return '/Pages/VCockpit/Instruments/FSS_B727/KH_FE_FPLAN/assets/img/compass.png';
    else if (val === 2) return '/Pages/VCockpit/Instruments/FSS_B727/KH_FE_FPLAN/assets/img/wrench.png';
    return '';
  });

  constructor(props: ControlsProps) {
    super(props);

    props.position.sub((p) => this.buttonName.set(p));
  }

  private cycle = (): void => {
    if (this.props.page === 0) SimVar.SetSimVarValue('L:KH_FE_FPLAN_P1', 'bool', true);
    else if (this.props.page === 1) SimVar.SetSimVarValue('L:KH_FE_FPLAN_P1', 'bool', false);
  };

  private toTop = (): void => {
    if (!this.props.containerRef.instance) return;

    this.props.containerRef.instance.scrollTop = 0;
  };

  private switchPosition = (): void => {
    if (this.props.position.get() === 1) SimVar.SetSimVarValue('L:KH_FE_FPLAN_BOARD', 'number', 2);
    else if (this.props.position.get() === 2) SimVar.SetSimVarValue('L:KH_FE_FPLAN_BOARD', 'number', 1);
  };

  public render = (): VNode => (
    <div id="KH_CTRL">
      {this.props.page === 1 && (
        <div ref={this.cycleRef} class="button">
          <img class="icon" src="/Pages/VCockpit/Instruments/FSS_B727/EFB/Images/get.png" />
        </div>
      )}
      <div ref={this.toTopRef} class="button d90">
        <img class="icon" src="/Pages/VCockpit/Instruments/FSS_B727/EFB/Images/get.png" />
      </div>
      <div ref={this.reloadRef} class="button">
        <img class="icon" src="/Pages/VCockpit/Instruments/FSS_B727/EFB/Images/cloud.png" />
      </div>
      <div ref={this.switchPosRef} class="button">
        <img class="icon" src={this.buttonName} />
      </div>
      {this.props.page === 0 && (
        <div ref={this.cycleRef} class="button d180">
          <img class="icon" src="/Pages/VCockpit/Instruments/FSS_B727/EFB/Images/get.png" />
        </div>
      )}
    </div>
  );

  public onAfterRender = (): void => {
    this.cycleRef.instance.onclick = this.cycle;
    this.toTopRef.instance.onclick = this.toTop;
    this.reloadRef.instance.onclick = this.props.reload;
    this.switchPosRef.instance.onclick = this.switchPosition;
  };
}
