import { Injectable } from '@angular/core';
import { LoadingController, AlertController } from '@ionic/angular';
import { HttpClient } from '@angular/common/http';
import { File} from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { Router } from  "@angular/router";

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

  constructor(
    private loadingCtrl: LoadingController, 
    private alertController: AlertController,
    private  httpClient: HttpClient,
    private file: File,
    private fileOpener: FileOpener,
    private  router:  Router
    ) {
    this.loader = this.loadingCtrl.create({
      message: "Please wait...",
    });
  }

  async presentAlert(headerPar, subtitlePar, messagePar, buttonsPar) {
  
    const alert = await this.alertController.create({
      header: headerPar,
      subHeader: subtitlePar,
      message: messagePar,
      buttons: buttonsPar
    });
    return alert.present();
  }

  loader;

  async showLoading() {
    this.loader = await this.loadingCtrl.create({
      message: "Please wait...",
    });
    return await this.loader.present();
  }

  closeLoading() {
    this.loader.dismiss();
  }

  getDateString(date: Date) :string
  {
    return date.getDay() + "-" + date.getMonth() + "-" + date.getFullYear();
  }

  static encodeBody(params) {
    var urlEncodedDataPairs = [];
    var key;
    for(key in params) {
      urlEncodedDataPairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
    }
    return urlEncodedDataPairs.join('&').replace(/%20/g, '+');
  }

  dateFormatConvert(date:string) :string{
    var array = date.split('-');
    return array[2]+"-"+array[1]+"-"+array[0];;
  }

  static getMIMEtype(extn){
    let ext=extn.toLowerCase();
    let MIMETypes={
      'txt' :'text/plain',
      'docx':'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'doc' : 'application/msword',
      'pdf' : 'application/pdf',
      'jpg' : 'image/jpeg',
      'bmp' : 'image/bmp',
      'png' : 'image/png',
      'gif' : 'image/gif',
      'xls' : 'application/vnd.ms-excel',
      'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'rtf' : 'application/rtf',
      'ppt' : 'application/vnd.ms-powerpoint',
      'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
    }
    return MIMETypes[ext];
  }

  downloadDocumento(fileUrl: string, nomeFile: string)
  {
    var path = "";
    path = this.file.externalDataDirectory;
    nomeFile = nomeFile.replace(/\//g, "-");
    this.download(fileUrl)
      .subscribe(
      (data) => { // Success
        this.file.writeFile(path, nomeFile, data, { replace: true }).then((fileEntry: FileEntry) => {
          console.log("File created!");
          this.presentAlert("Avviso", "", 'File Salvato: '+fileEntry.toURL(), ["OK"]);
          //Open with File Opener plugin
          let fileExtn=nomeFile.split('.').reverse()[0];
          let fileMIMEType=UtilService.getMIMEtype(fileExtn);
          this.fileOpener.open(fileEntry.toURL(), fileMIMEType)
          .then(() => {
            console.log('File is opened');
          })
          .catch(e => {
            this.presentAlert("Avviso", "", 'Apertura in errore:' + e, ["OK"]);
            console.log('Error openening file', e);
          });
        
        },
        (error) =>{
          console.error(error);
        }
      );
    });
  }

  download(url)
  {
    return this.httpClient.get(url, {responseType: "blob"});
  }

  apriPagina(pagina:string)
  {
    switch(pagina)
    {
      case "home":
      {
        this.router.navigateByUrl('home/index');
        break;
      }
      case "documenti":
      {
        this.router.navigateByUrl('home/documenti');
        break;
      }
      case "interviste":
      {
        this.router.navigateByUrl('home/interviste');
        break;
      }
      case "pareri":
      {
        this.router.navigateByUrl('home/parere');
        break;
      }
      case "segreteria":
      {
        this.router.navigateByUrl('home/segreteria');
        break;
      }
      case "change-password":
      {
        this.router.navigateByUrl('home/change-pwd');
        break;
      }
    }
  }
}
