import {Injectable} from '@angular/core'
import {OrientationType, ScreenOrientation} from '@capawesome/capacitor-screen-orientation'
import {Capacitor} from '@capacitor/core'

@Injectable({
  providedIn: 'root'
})
export class OrientationService {

  isLandscape = false
  isPortrait = true
  isNative = Capacitor.isNativePlatform()

  #currentOrientation: OrientationType = OrientationType.PORTRAIT

  constructor() {
    ScreenOrientation.getCurrentOrientation().then(o => this.#setOrientation(o.type))
  }

  /**
   * Change the orientation of the app to landscape.
   * This LOCKS changing orientation through the accelerometer.
   */
  async setAndLockLandscape(): Promise<void> {
    await this.#setOrientation(OrientationType.LANDSCAPE)
  }

  /**
   * Change the orientation of the app to portrait.
   * This LOCKS changing orientation through the accelerometer.
   */
  async setAndLockPortrait(): Promise<void> {
    await this.#setOrientation(OrientationType.PORTRAIT)
  }

  /**
   * Change the current orientation, lock it and set the booleans that indicate the current orientation.
   *
   * @param orientation The new orientation.
   * @private
   */
  async #setOrientation(orientation: OrientationType) {
    this.#currentOrientation = orientation
    await this.#lockOrientation()
    this.#setOrientationBooleans()
  }

  /**
   * Change the orientation of the app to this.#currentOrientation.
   * This LOCKS changing orientation through the accelerometer.
   *
   * @private
   */
  async #lockOrientation(): Promise<void> {
    if (this.isNative) {
      await ScreenOrientation.lock({type: this.#currentOrientation})
    }
  }

  /**
   * Set the boolean variables isLandscape and isPortrait.
   *
   * @private
   */
  #setOrientationBooleans() {
    this.#setIsPortrait()
    this.#setIsLandscape()
  }

  /**
   * Set the boolean variable isPortrait based on the current orientation.
   *
   * @private
   */
  #setIsPortrait(): void {
    this.isPortrait = this.#currentOrientation === OrientationType.PORTRAIT ||
      this.#currentOrientation === OrientationType.PORTRAIT_SECONDARY ||
      this.#currentOrientation === OrientationType.PORTRAIT_PRIMARY
  }

  /**
   * Set the boolean variable isLandscape based on the current orientation.
   *
   * @private
   */
  #setIsLandscape(): void {
    this.isLandscape = this.#currentOrientation === OrientationType.LANDSCAPE ||
      this.#currentOrientation === OrientationType.LANDSCAPE_SECONDARY ||
      this.#currentOrientation === OrientationType.LANDSCAPE_PRIMARY
  }

}
