import { Component } from '@angular/core';
import {CurrencyPipe} from '@angular/common';
import { NavController, ModalController, LoadingController, AlertController, ActionSheetController, Platform } from 'ionic-angular';

import { DoctorService } from '../../services/doctor.service';
import { Pata } from '../../pata';
import { environment } from "../../environments/environment"
import * as moment from 'moment';
import { Camera } from '@ionic-native/camera';
import { RecetaPage } from './receta';

@Component({
  selector: 'page-receta-add',
  templateUrl: 'add.html'
})
export class RecetaAddPage {
  
  public images: any = [];
  public doctor: any = { name: '', card_code: '' };
  public inicio: string= '';
  public final: string = '';
  public gramos: number = 0;
  token: string = '';
  base64Image: string;
  public loading: any = null;
  public maxDate: string = '';
  public minDate: string = '';
  public showWarning: boolean = false;

  constructor(
    public navCtrl: NavController,
    public modalCtrl: ModalController,
    public loadingCtrl: LoadingController,
    private alertCtrl: AlertController,
    public service: Pata,
    public platform: Platform,
    public camera: Camera,
    public actionSheetCtrl: ActionSheetController,
    private doctorService: DoctorService) {
   
      this.doctorService.getToken().subscribe((data:any) => {
        this.token = data;
      });
      let now = moment();
      let now2 = moment();
      now.add(240, 'M');
      now2.subtract(36, 'M');
      
      this.maxDate = now.format("YYYY-MM-DD");
      this.minDate = now2.format("YYYY-MM-DD");
      this.searchRecetaPending();
  }
  ionViewDidEnter(){
    
  }

  searchRecetaPending() {
    this.doctorService.getRecetas().subscribe((data:any) => {
      for (let x = 0; x < data.data.length; x++) {
        if (parseInt(data.data[x].status) == 0) {
          this.showWarning = true;
          break;
        }
      }
      
    }, (err) => {
      
    })
  }
  public takePicture() {
    if (this.platform.is('cordova')) {
    this.camera.getPicture({
        destinationType: this.camera.DestinationType.DATA_URL,
        quality: 100,
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.PICTURE,
        correctOrientation: true
    }).then((imageData) => {
        this.processTake(imageData);
    }, (err) => {      
        console.log(err);
    });
    } else {
      this.processTake(" ");
    }
  }
  private openGallery (): void {
    let cameraOptions = {
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.camera.DestinationType.DATA_URL,      
      quality: 60,
      targetWidth: 320,
      targetHeight: 320,
      encodingType: this.camera.EncodingType.JPEG,      
      correctOrientation: true
    }
    this.camera.getPicture(cameraOptions)
      .then(file_uri => {
        this.processTake(file_uri);
      }, 
      err => {
        console.log(err)
      }); 
  }
  addFotoReceta() {
    const actionSheet = this.actionSheetCtrl.create({
      title: 'Sube una imagen',
      buttons: [
        {
          text: 'Usar mi cámara',
          handler: () => {
            this.takePicture();
          }
        },{
          text: 'Usar galeria',
          handler: () => {
            this.openGallery();
          }
        },{
          text: 'Cancelar',
          role: 'cancel',
          handler: () => {
            
          }
        }
      ]
    });
    actionSheet.present();
  }
  optionsImagen(index:number) {
    const actionSheet = this.actionSheetCtrl.create({
      title: 'Opciones de la imagen',
      buttons: [
        {
          text: 'Eliminar',
          role: 'destructive',
          handler: () => {
            this.images.splice(index, 1);
          }
        },{
          text: 'Cancelar',
          role: 'cancel',
          handler: () => {
            
          }
        }
      ]
    });
    actionSheet.present();
  }
  save() {
    let ini = moment(this.inicio);
    let end = moment(this.final);

    if (this.images.length == 0) {
      this.service.showMsg("Es necesario cargar a lo menos una imagen de receta");
    }
    else if (this.gramos < 1) {
      this.service.showMsg("Gramos diarios debe ser superior a 0");
    }
    else if ( !ini.isValid() || !end.isValid() ) {
      this.service.showMsg("Debe indicar fecha de inicio y término");
    }
    else if (ini.isAfter(end)) {
      this.service.showMsg("Fecha de inicio debe ser inferior a fecha de término");
    }
    else if (this.doctor.name == "" || this.doctor.card_code == "") {
      this.service.showMsg("Ingrese datos del médico firmante");
    }
    else {
      this.doctorService.savePrescription({
        start: ini.format("YYYY-MM-DD"),
        end: end.format("YYYY-MM-DD"),
        grs: this.gramos,
        image: this.images.join(','),
        doctorname: this.doctor.name,
        doctorcode: this.doctor.card_code
      }).subscribe((data:any) => {
        if (data.res == "OK") {
          this.service.showOk("Receta enviada con éxito");
          this.navCtrl.setRoot(RecetaPage, {}, { direction: 'forward' });
        } else {
          this.service.showMsg(data.msg);
        }
      });
    }
  } 
  private dataURItoBlob(dataURI) {
    var byteString;

    if (dataURI.split(',')[0].indexOf('base64') >= 0)
      byteString = atob(dataURI.split(',')[1]);
    else
      byteString = (dataURI.split(',')[1]);

    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {
      type: mimeString
    });
  }
  public processTake(imageData) {

    this.base64Image = "data:image/jpeg;base64," + imageData;
    this.loading = this.loadingCtrl.create({content:'subiendo...'});
    this.loading.present();   

    var self0 = this;
    var blob = this.dataURItoBlob(this.base64Image);

    var objURL = window.URL.createObjectURL(blob);
    var image = new Image();
    image.src = objURL;
    window.URL.revokeObjectURL(objURL);

    var url = window.URL.createObjectURL(blob);

    var formData = new FormData();
    formData.append('avatar', blob, 'avatar.jpg');
    
    var xhr = new XMLHttpRequest();
    xhr.open("post", environment.apiUrl+"prescriptions/files/upload");
    xhr.setRequestHeader("Authorization", self0.token);

    xhr.onreadystatechange = function () {

      if(xhr.readyState === 4 && xhr.status === 200) {
        var uri = xhr.responseText;
        self0.loading.dismiss();

        if (uri.indexOf('error') > -1) {
          self0.service.logError({}, 'Error al procesar la solicitud. Inténtelo más tarde.');
        }
        else {
          console.log(uri);
          let json = JSON.parse(uri);
          self0.addUploadOK(json);          
        }
      }
    };
    xhr.send(formData);
  }
  b64toBlob(b64, onsuccess, onerror) {
    var img = new Image();

    img.onerror = onerror;

    img.onload = function onload() {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;

        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

        canvas.toBlob(onsuccess);
    };

    img.src = b64;
  }  
  addUploadOK(uri: any) {
    this.images.push(uri.url);
  }

}


