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';
import { BehaviorSubject} from  'rxjs';
import { Struttura } from '../interface/struttura';

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 logout() {
    const alert = await this.alertController.create({
      header: 'Conferma',
      message: 'Vuoi davvero uscire?',
      buttons: [
        {
          text: 'No',
          role: 'cancel',
          handler: () => {
          }
        },
        {
          text: 'Si',
          handler: () => {
            this.logoutUser();
            this.router.navigateByUrl('login');
          }
        }
      ]
    });
    alert.present();
  }

  authSubject  =  new  BehaviorSubject(false);

  async logoutUser() {
    this.storage.set("logged",false).then((successData)=>{
      console.log("Data Stored");
      console.log(successData);
    })
    this.authSubject.next(false);
  }

  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;
  private static strutturaSel:Struttura;
  public static strutture: Struttura[];
  public static titoloPagina:string = "";

  static setStruttura(id:number)
  {
    if(this.strutture.length > 0)
    { 
      this.strutture.forEach(function (value) {
        if(value.id == id) this.utilService.setStrutturaSel(value);
        this.strutturaSel = this.utilService.getStrutturaSel();
      });
    }
  }

  getStruttura(id:number): Promise<any>
  {
    if(UtilService.strutture == null) return;
    if(UtilService.strutture.length > 0)
    { 
      let promiseChain: Promise<any> = Promise.resolve();
      UtilService.strutture.forEach(value => {
        if(value.id == id) promiseChain = promiseChain.then(
          () => value
        )
      });
      return promiseChain;
    }
  }

  getStrutturaSel()
  {
    return UtilService.strutturaSel;
  }

  setStrutturaSel(s: Struttura)
  {
    UtilService.strutturaSel = s;
  }

  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() {
    if(this.platform.is("ios")) return null;
    this.loader = await this.loadingCtrl.create({
      message: "Please wait...",
    });
    this.loaders.push(this.loader);
    return await this.loader.present();
  }

  closeLoading() {
    if(this.platform.is("ios")) return null;
    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>;
  datiScaricati: Array<Blob>;
  files: Array<Pair>;
  count: number;
  total: number;

  shareDocumenti(fileSel : Array<Pair>)
  {
    this.count = 0;
    this.fileScaricati = new Array();
    this.datiScaricati = new Array();
    this.files = fileSel;
    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 = "";
    if(this.platform.is("ios")) path = this.file.dataDirectory;
    else path = this.file.externalDataDirectory;
    var nomeFile : string = fileInfo.key;
    nomeFile = nomeFile.replace(/\//g, "-");
    await this.download(fileInfo.value)
      .subscribe(
      (data) => { // Success
        if(this.platform.is("ios"))
        {
          this.fileScaricati.push(fileInfo.value);
          this.count++;
        }
        else
        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 = "";
    if(this.platform.is("ios")) path = this.file.dataDirectory;
    else 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 = "";
    if(this.platform.is("ios")) path = this.file.dataDirectory;
    else 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)
  {
    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"]);
  }

  stampaAvviso(text: string)
  {
    this.presentAlert("Avviso", "", text, ["OK"]);
  }

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

  async apriPagina(pagina:string)
  {
    switch(pagina)
    {
      case "home":
      {
        
        UtilService.titoloPagina = '';
        this.events.publish('functionCall:cambiaTitolo', null);
        this.router.navigateByUrl('home/index');
        break;
      }
      case "documenti":
      {
        this.translate.get('titolo_documenti').subscribe(
          value => {
            UtilService.titoloPagina = value;
            this.events.publish('functionCall:cambiaTitolo', null);
          });
        this.router.navigateByUrl('home/documenti');
        break;
      }
      case "interviste":
      {
        this.translate.get('interviste_titolo').subscribe(
          value => {
            UtilService.titoloPagina = value;
            this.events.publish('functionCall:cambiaTitolo', null);
          });
        this.router.navigateByUrl('home/interviste');
        break;
      }
      case "pareri":
      {
        this.translate.get('parere_titolo').subscribe(
          value => {
            UtilService.titoloPagina = value;
            this.events.publish('functionCall:cambiaTitolo', null);
          });
        this.router.navigateByUrl('home/parere');
        break;
      }
      case "segreteria":
      {
        this.translate.get('segreteria_titolo').subscribe(
          value => {
            UtilService.titoloPagina = value;
            this.events.publish('functionCall:cambiaTitolo', null);
          });
        this.router.navigateByUrl('home/segreteria');
        break;
      }
      case "bi":
      {
        this.router.navigateByUrl('home/bi');
        break;
      }
      case "change-password":
      {
        this.translate.get('change_password').subscribe(
          value => {
            UtilService.titoloPagina = value;
            this.events.publish('functionCall:cambiaTitolo', null);
          });
        this.router.navigateByUrl('home/change-pwd');
        break;
      }
    }
  }
}
