import { Pair } from './../interface/pair';
import { Injectable } from '@angular/core';
import { LoadingController, AlertController, Platform, Events } 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';
import { TranslateService } from '@ngx-translate/core';
import { Storage } from  '@ionic/storage';

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,
    private  storage:  Storage, 
    public translate: TranslateService,
    public events: Events
    ) {
    this.loaders = new Array();
    this.loader = this.loadingCtrl.create({
      message: "Please wait...",
    });
    this.loaders.push(this.loader);
    this.languageSelected = "";
  }

  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>;
  private languageSelected:string;

  loadLingua()
  {
    this.storage.get("lingua").then((data)=>{
      if(data != null)
      {
        this.languageSelected = data;
        this.translate.setDefaultLang(data);
        this.translate.use(data);
        this.events.publish('functionCall:linguaCambiata', null);
      }
    });
  }

  setLingua(lingua: string)
  {
    this.languageSelected = lingua;
    this.storage.set("lingua",lingua).then((successData)=>{
      console.log("Salvata lingua: "+lingua);
    });
  }

  getLingua():string
  {
    return this.languageSelected;
  }

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

  getLanguageList() : Array<Pair>
  {
    var langs = new Array<Pair>();
    let lang : Pair = {
      'key' :'it',
      'value': 'italiano',
      'type': ''
    }
    langs.push(lang);
    return langs;
  }

  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>;
  count: number;
  total: number;

  shareDocumenti(fileSel : Array<Pair>)
  {
    this.count = 0;
    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++;
    }*/
    this.total = fileSel.length;
    fileSel.forEach(this.saveFile, this);
    if(this.count == this.total) this.share();
    else setTimeout(() => {
      this.share()
    }, 1000);
  }

  share(){
    if(this.count != this.total) setTimeout(() => {
      this.share()
    }, 1000);
    else{
      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 dei file', ["OK"]);
        console.log('Errore durante la condivisione dei file:' + e);
      });
    }
  }

  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());
          this.count++;
        },
        (error) =>{
          this.count++;
          console.log(error);
          this.presentAlert("Avviso", "", 'Errore durante il salvataggio del file:' + nomeFile, ["OK"]);
        }
      );
    });
  }

  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', ["OK"]);
            console.error(e);
          });
        },
        (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 file in errore', ["OK"]);
            console.log('Error openening file', e);
          });
        
        },
        (error) =>{
          console.error(error);
        }
      );
    });
  }

  stampaErrore(text: string, error)
  {
    var text = "Errore durante richiesta delle fatture";
    if(error != null && error.errorMsg != null) console.log(text+": "+error.errorMsg);
    else if(error!=null) console.log(text+": "+error);
    else console.log(text);
    this.presentAlert("Errore", "", text, ["OK"]);
  }

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