import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { Pair } from './../interface/pair';
import { Injectable } from '@angular/core';
import { LoadingController, AlertController, Platform } 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";
import { SocialSharing } from '@ionic-native/social-sharing/ngx';

const delay = ms => new Promise(res => setTimeout(res, ms));

const wait = async () => {
  await delay(3000);
  console.log("Waited 3s");
}

@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,
    public platform: Platform,
    private socialSharing: SocialSharing
    ) {
    this.loaders = new Array();
    this.loader = this.loadingCtrl.create({
      message: "Please wait...",
    });
    this.loaders.push(this.loader);
  }

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

  loader;
  loaders: Array<any>;

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

  closeLoading() {
    if(this.loaders.length > 0)
    {
      this.loader = this.loaders.pop();
      this.loader.dismiss();
    }
    else{
      setTimeout(() => {
        this.secondClose()
      }, 2000)
    }
  }

  secondClose()
  {
    if(this.loaders.length > 0)
    {
      this.loader = this.loaders.pop();
      this.loader.dismiss();
    }
  }

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

  getAndroidDateString(date: Date) :string
  {
    return date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getUTCFullYear();
  }

  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{
    if(this.platform.is("desktop"))
    {
      var array = date.split('-');
      return array[2]+"-"+array[1]+"-"+array[0];
    }
    return date;
  }

  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];
  }

  static wait()
  {
    wait();
  }

  fileScaricati: Array<string>;

  shareDocumenti(fileSel : Array<Pair>)
  {
    this.fileScaricati = new Array();
    this.showLoading();
    /*var i = 0;
    while(i < fileSel.length)
    {
      var fileInfo : Pair = fileSel.pop();
      var path = this.file.externalDataDirectory;
      var
      nomeFile = nomeFile.replace(/\//g, "-");
      this.download(fileInfo.value)
        .subscribe(
        (data) => { // Success
          this.file.writeFile(path, fileInfo.key, data, { replace: true }).then((fileEntry: FileEntry) => {
            this.fileScaricati.push(fileEntry.toURL());
          },
          (error) =>{
            console.log(error);
          }
        );
      });
      i++;
    }*/
    fileSel.forEach(this.saveFile, this);
    setTimeout(() => {
      this.share()
    }, 10000*fileSel.length);
  }

  share(){
    this.closeLoading();
    this.socialSharing.share(null, null, this.fileScaricati, null).then(() => {
      console.log("File condiviso con successo!");
    }).catch((e) => {
      this.presentAlert("Avviso", "", 'Errore durante la condivisione del file:' + e, ["OK"]);
    });
  }

  async saveFile(fileInfo: Pair, index)
  {
    var path = this.file.externalDataDirectory;
    var nomeFile : string = fileInfo.key;
    nomeFile = nomeFile.replace(/\//g, "-");
    await this.download(fileInfo.value)
      .subscribe(
      (data) => { // Success
        this.file.writeFile(path, nomeFile, data, { replace: true }).then((fileEntry: FileEntry) => {
          this.fileScaricati.push(fileEntry.toURL());
        },
        (error) =>{
          console.log(error);
        }
      );
    });
  }

  shareDocumentoBis(fileUrl: string, nomeFile: string)
  {
    var path = "";
    path = this.file.externalDataDirectory;
    nomeFile = nomeFile.replace(/\//g, "-");
    this.showLoading();
    this.download(fileUrl)
      .subscribe(
      (data) => { // Success
        this.file.writeFile(path, nomeFile, data, { replace: true }).then((fileEntry: FileEntry) => {
          console.log("File created!");
          this.fileScaricati.push(fileEntry.toURL());
        },
        (error) =>{
          console.error(error);
        }
      );
    });
  }

  shareDocumento(fileUrl: string, nomeFile: string)
  {
    var path = "";
    path = this.file.externalDataDirectory;
    nomeFile = nomeFile.replace(/\//g, "-");
    this.showLoading();
    this.download(fileUrl)
      .subscribe(
      (data) => { // Success
        this.file.writeFile(path, nomeFile, data, { replace: true }).then((fileEntry: FileEntry) => {
          console.log("File created!");
          this.closeLoading();
          this.socialSharing.share(null, null, fileEntry.toURL(), null).then(() => {
            console.log("File condiviso con successo!");
          }).catch((e) => {
            this.presentAlert("Avviso", "", 'Errore durante la condivisione del file:' + e, ["OK"]);
          });
        },
        (error) =>{
          console.error(error);
        }
      );
    });
  }

  downloadDocumento(fileUrl: string, nomeFile: string)
  {
    var path = "";
    path = this.file.externalDataDirectory;
    nomeFile = nomeFile.replace(/\//g, "-");
    this.showLoading();
    this.download(fileUrl)
      .subscribe(
      (data) => { // Success
        this.file.writeFile(path, nomeFile, data, { replace: true }).then((fileEntry: FileEntry) => {
          console.log("File created!");
          this.closeLoading();
          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 "bi":
      {
        this.router.navigateByUrl('home/bi');
        break;
      }
      case "change-password":
      {
        this.router.navigateByUrl('home/change-pwd');
        break;
      }
    }
  }
}
