import {Injectable} from '@angular/core'
import { AlertController } from 'ionic-angular';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Storage } from '@ionic/storage';
import * as global from './global';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import { of } from 'rxjs/observable/of';

@Injectable()
export class Lipigas {
  
  public p: any;
  send: any[] = [];
  backup: any[] = [];
  public perfil: any;

  constructor(public alertCtrl: AlertController, private storage: Storage, private http: Http) {

  }
  
  logError(o: any, msg?: string) {
    if (!msg) { msg = 'Ocurrio un error al procesar su solicitud. Intente más tarde'; }
    let alert = this.alertCtrl.create({
      title: 'Error',
      subTitle: msg,
      buttons: ['OK']
    });
    alert.present();
  	if (o !== null) { console.log(o); }
  }
  showMsg(msg: string) {
    let alert = this.alertCtrl.create({
      title: '',
      cssClass: 'alertSuccess',
      subTitle: msg,
      buttons: ['Aceptar']
    });
    alert.present();
  }

  showDater(msg: string) {
    let alert = this.alertCtrl.create({
      title: '',
      cssClass: 'alertSuccess',
      subTitle: '<h3>Activar Lipipuntos</h3>Selecciona la fecha y horario<br /><br /><input type="date" #fechaSolicitud />&nbsp;<img src="assets/icon/solicitar.blue.png" />&nbsp;<select #horaSolicitud><option value="AM">AM</option><option value="PM">PM</option></select><br /><br /><button class="shadow" ion-button (click)="postSolicitar(fechaSolicitud.value, horaSolicitud.value);">Solicitar</button><button class="shadow" ion-button (click)="closePopup();">Cancelar</button>',
      buttons: ['Aceptar']
    });
    alert.present();
  }

  private headers() {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Content-Type', 'application/json');
      headers.append('Authorization', 'Bearer '+this.perfil.token);
      let options = new RequestOptions({ headers: headers });
      return options;
  }

  sync(origin: string) {
    console.log("sync start now from ", origin, new Date());
    if (localStorage.getItem("LipigasPersonas")) {
      this.perfil = JSON.parse(localStorage.getItem("LipigasPersonas"));
      var continuar = 0;
      this.send = [];

      if (this.perfil.hasOwnProperty("roles")) {
        for (var i = 0; i < this.perfil.roles.length ; i++) {
          if (this.perfil.roles[i] == "enrolador") {
            continuar = 1;
          }
        }
      }

      if (continuar == 1) {
        var promesas = [];
        this.storage.get("cursos").then((x) => {
          if (x != null) {
            for (var i = 0;i < x.length; i++) {
              for (var j = 0;j < x[i].modulos.length; j++) {
                var id = x[i].modulos[j].id;
                var tipo = x[i].modulos[j].tipo;
                promesas.push(this.storage.get("als_"+id+"_"+tipo));
              }
            }

            // esperar el storage de todos los cursos
            try {
              Observable.forkJoin(promesas).subscribe( k => {

                if (k.length > 0) {
              
                  for (var m = 0;m < k.length; m++) {
                    
                    var sendpost = [];
                    var mdl_id = 0;
                    var mdl_tipo = '';

                    for (var h = 0; h < (<any>k[m]).length ; h++ ) {
                      var w = k[m][h];
                      mdl_id = w.mdl_id;
                      mdl_tipo = w.mdl_tipo;
                      if (w.sync == 0 && w.estado == 1) {
                        sendpost.push({
                          rut: w.rut, 
                          motivo: w.motivo, 
                          latitud: w.latitud, 
                          longitud: w.longitud, 
                          fecha: w.fecha, 
                          offline: w.offline, 
                          metodo: w.metodo
                        });
                      }
                    }

                    if (sendpost.length > 0) {
                      this.send.push(this.http.post(global.api+'/cursos/enrolar/'+mdl_id+'/'+mdl_tipo+'/alumnos', { registros: sendpost }, this.headers()).map(res => res.json()));
                      this.backup.push({
                        mdl_id: mdl_id,
                        mdl_tipo: mdl_tipo
                      })
                    }
                  }

                  if (this.send.length > 0) {

                    Observable.forkJoin(this.send).subscribe(res => {
                      
                      var procesos = [];
                      var ruts = [];
                      for (var a = 0; a < res.length; a++) {
                        var mdl_id = this.backup[a].mdl_id;
                        var mdl_tipo = this.backup[a].mdl_tipo;
                        var actualiza = 0;
                        for (var b = 0; b < (<any>res[a]).respuesta.length; b++) {
                          if ((<any>res[a]).respuesta[b].resultado == 1) {
                            ruts.push((<any>res[a]).respuesta[b].rut);
                            actualiza = 1;
                          }
                        }
                        if (actualiza == 1) {
                          procesos.push(this.storage.get("als_"+mdl_id+"_"+mdl_tipo));
                        }
                      }

                      if (procesos.length > 0) {
                        Observable.forkJoin(procesos).subscribe(ok => {

                          for (var n = 0; n < ok.length; n++) {
                            for (var m = 0; m < (<any>ok[n]).length; m++) {

                              // all ruts
                              for (var p = 0; p < ruts.length; p++) {
                                if (ok[n][m].rut == ruts[p]) {
                                  ok[n][m].sync = 1;
                                }
                              }
                            }

                            this.storage.set("als_"+ok[n][0].mdl_id+"_"+ok[n][0].mdl_tipo, ok[n]);
                            this.updateSync(ok[n][0]);
                          }

                          console.log('End sync - send all ok', new Date());
                          if (origin != 'manual') { setTimeout(() => { this.sync('native'); }, 60000); }

                        });   
                      }
                      else {
                        console.log('End sync - all send but without process', new Date());
                        if (origin != 'manual') { setTimeout(() => { this.sync('native'); }, 60000); } 
                      }
                 
                    });
                  }
                  else {
                    console.log('End sync - no send pending', new Date());
                    if (origin != 'manual') { setTimeout(() => { this.sync('native'); }, 60000); }     
                  }
                }
                else {
                  console.log('End sync - no subscribers on get storage', new Date());
                  if (origin != 'manual') { setTimeout(() => { this.sync('native'); }, 60000); }
                } 
              },
              e => {
                  console.log('End sync - error on request', new Date());
                  if (origin != 'manual') { setTimeout(() => { this.sync('native'); }, 60000); }
              });
            } catch (e) {
                console.log('End sync - error on request', new Date(), e);
                if (origin != 'manual') { setTimeout(() => { this.sync('native'); }, 60000); }
            }
          }
          else {
            console.log('End sync - cursos = 0', new Date());
            if (origin != 'manual') { setTimeout(() => { this.sync('native'); }, 60000); }
          }
        });     
      }
    }
    else {
      console.log('End sync - no cursos key', new Date());
      if (origin != 'manual') { setTimeout(() => { this.sync('native'); }, 60000); }
    }
  }
  updateSync(idModulo: number) {

    this.storage.get("cursos").then((v) => {
    
      if (v.length > 0) {

        for (var i = 0; i < v.length; i++) {
          if (v[i].modulos.length > 0) {
            for (var j = 0; j < v[i].modulos.length; j++) {

              if (v[i].modulos[j].id == idModulo) {
                var d = new Date();
                var ahora2 =
                    ("00" + d.getDate()).slice(-2) + "/" + 
                    ("00" + (d.getMonth() + 1)).slice(-2) + "/" + 
                    d.getFullYear() + " " + 
                    ("00" + d.getHours()).slice(-2) + ":" + 
                    ("00" + d.getMinutes()).slice(-2) + ":" + 
                    ("00" + d.getSeconds()).slice(-2);

                this.storage.set("link_"+v[i].id,ahora2);

                break;
              }
            }
          }
        }
      }

    });
  }

}