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

import { DoctorService } from '../../services/doctor.service';
import { Pata } from '../../pata';
import { environment } from "../../environments/environment"
import * as moment from 'moment';
import { VerRecorridoPage } from '../ver-recorrido/ver-recorrido';
import { RecetaAddPage } from './add';

@Component({
  selector: 'page-receta',
  templateUrl: 'receta.html'
})
export class RecetaPage {
  shownGroup = null;
  prescriptions: any = [];
  constructor(
    public navCtrl: NavController,
    public modalCtrl: ModalController,
    public loadingCtrl: LoadingController,
    private alertCtrl: AlertController,
    public service: Pata,
    private doctorService: DoctorService) {
  }
  ionViewDidEnter(){
    this.getRecetas();
  }
  getRecetas() {
    let loading = this.loadingCtrl.create();
    loading.present();
    this.doctorService.getRecetas().subscribe((data:any) => {
      this.prescriptions = data.data;
      loading.dismiss();
    }, (err) => {
      loading.dismiss();
    })
  }
  eliminarReceta(index:number) {
    let id = this.prescriptions[index].id;
    let alert = this.alertCtrl.create({
      title: '',
      message: '¿Desea eliminar esta solicitud?',
      buttons: [
        { text: 'Cancel', role: 'cancel', handler: () => { } },
        { text: 'OK', handler: () => { this.deleteRecetaOK(id); } }
      ]
    });
    alert.present();
  } 
  deleteRecetaOK(id){
    let loading = this.loadingCtrl.create();
    loading.present();

    this.doctorService.deleteReceta(id).subscribe((data:any)=>{
      loading.dismiss();
      if (data.res == "OK"){
        this.service.showOk();
        this.getRecetas();        
      } else{
        this.service.showMsg(data.msg);
      }
    },(err)=>{
      this.service.showMsg("No fue posible eliminar la solicitud");
    });
  } 
  dateformat(fecha){
    var fecha_mm = moment(fecha);
    return moment(fecha_mm.format(),moment.ISO_8601).format();
  }
  doRefresh(refresher) {
    this.getRecetas();
    setTimeout(() => {
      refresher.complete();
    }, 0);
  }
  addReceta() {
    this.navCtrl.push(RecetaAddPage);
  }

}


