import { Injectable, AfterViewInit } from "@angular/core";
import { Events, Platform } from "@ionic/angular";
import { CommonService } from "../common/common.service";
import { Keyboard } from "@ionic-native/keyboard/ngx";
import { KeyboardStatusModel } from "./keyboard-status.model";

@Injectable({
  providedIn: "root"
})
export class KeyboardService {
  public static KEYBOARD_STATUS = "keyboard-status-event";
  public static keyboardOpened = false;
  public static isOpened() {
    return KeyboardService.keyboardOpened;
  }

  constructor(
    public events: Events,
    public cs: CommonService,
    public keyboard: Keyboard,
    public platform: Platform
  ) {}

  public watchKeyboard() {
    this.platform.ready().then(() => {
      window.addEventListener('keyboardDidHide', () => {
        this.publishEvent(false);
      });

      window.addEventListener('keyboardDidShow', () => {
        this.publishEvent(true);
      });

      /*
      this.keyboard.onKeyboardHide().subscribe( (observer) => {
        
      });
      
      this.keyboard.onKeyboardHide().subscribe(() => {
        this.publishEvent(false);
      });
      this.keyboard.onKeyboardShow().subscribe(() => {
        this.publishEvent(true);
      });
      */
    });
  }

  private publishEvent(opened: boolean) {
    KeyboardService.keyboardOpened = opened;
    this.events.publish(
      KeyboardService.KEYBOARD_STATUS,
      new KeyboardStatusModel(opened)
    );
  }
}
