import { Injectable } from '@angular/core';
import { Diagnostic } from '@ionic-native/diagnostic/ngx';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { Observable } from 'rxjs';
import { SubjectSubscriber } from 'rxjs/internal/Subject';



@Injectable({
  providedIn: 'root'
})
export class DevicePermissionsService {
  public static granted = 'granted';
  public camera;
  public mic;
  public storage;
  public onSucess;
  public onerror;

  constructor(public diagnostic: Diagnostic,
    public cs: CommonService) { }

    public requestCameraPermission(camera: boolean, mic: boolean, storage: boolean): Observable<boolean> {
      this.camera = camera;
      this.mic = mic;
      this.storage = storage;
      return  Observable.create( observer => {
        this.requestCamera( observer);
      });
    }

  public requestCamera(observer: any) {
    this.diagnostic.isCameraAvailable().then((isAvailable) => {
      if (isAvailable) {
        if ( this.mic ) {
          this.requestMicophonePermission(observer);
        } else {
          this.observerDone(observer, true);
        }
      } else {
        this.diagnostic.requestCameraAuthorization(false).then((value) => {
          // alert( JSON.stringify(value));
          if (value.toLowerCase() === DevicePermissionsService.granted) {
            if ( this.mic ) {
              this.requestMicophonePermission(observer);
            } else {
              this.observerDone(observer, true);
            }
          } else {
            this.cameraError(observer);
          }
        });
      }
    }, () => {
      this.observerDone(observer, false);
    });
  }

  

  private cameraError(observer) {
    this.cs.presentConfirmDialog('camera permission required', () => {
      this.requestCamera(observer);
    }, () => {
      this.observerDone(observer, false);
    });
  }

  

  private requestMicophonePermission(observer: any) {
    this.diagnostic.isMicrophoneAuthorized().then((isAvailable) => {

      if (isAvailable) {
        this.observerDone(observer, true);
      } else {
        this.diagnostic.requestMicrophoneAuthorization().then((value) => {
          if (value.toLowerCase() === DevicePermissionsService.granted) {
            this.observerDone(observer, true);
          } else {
            this.micError(observer);
          }
        });
      }

    }, () => {
      this.observerDone(observer, false);
    });
    // // Checks microphone permissions
  }

  private micError(observer) {
    this.cs.presentConfirmDialog('Michrophone permission required', () => {
      this.requestMicophonePermission(observer);
    }, () => {
      this.observerDone(observer, false);
    });
  }

  private observerDone (observer: any, success: boolean ) {
    observer.next( success ) ;
    observer.complete();
  }
}
