import { Component, OnDestroy } from '@angular/core';
import { NavController, ViewController, NavParams, LoadingController, AlertController } from 'ionic-angular';
import { DoctorService } from '../../services/doctor.service';
import { ModalCheckout } from '../checkout/checkout';

@Component({
  selector: 'page-cart',
  templateUrl: 'cart.html'
})
export class ModalCart implements OnDestroy {
  public msg: string;
  public cartFull: any = null;
  constructor(public viewCtrl: ViewController, public navCtrl: NavController,public alertCtrl: AlertController, public loadingCtrl: LoadingController, public params: NavParams,public doctorService: DoctorService) {
    /*this.msg = params.get('msg');*/
    /*this.renderer.addClass(document.body.querySelector("ng-component.app-root"), 'blur');*/
    this.doctorService.finishCompra.subscribe((data:any) => {
      this.viewCtrl.dismiss(data);
    });
    let load = this.loadingCtrl.create({content: 'actualizando...'});
    load.present();
    this.doctorService.getCart().subscribe((data:any) => {
      load.dismiss();
      this.cartFull = data.data;
    });
  }

  closeCart() {
    let data = this.cartFull;
    this.viewCtrl.dismiss(data);
  }

  add(index: number) {
    this.cartFull.items[index].qty++;
    this.cartFull.items[index].total = (this.cartFull.items[index].price * this.cartFull.items[index].qty);
    this.doctorService.addCartItem
  }
  remove(index: number) {
    if (this.cartFull.items[index].qty > 1) {
      this.cartFull.items[index].qty--;
      this.cartFull.items[index].total = this.cartFull.items[index].price * this.cartFull.items[index].qty;
    }
  }
  delete(index: number) {
    let alert = this.alertCtrl.create({
      title: 'Eliminar linea',
      message: '¿Deseas eliminar '+this.cartFull.items[index].name+'?',
      buttons: [
        {
          text: 'Cancelar',
          role: 'cancel',
          handler: () => {
            
          }
        },
        {
          text: 'Eliminar',
          handler: () => {
            this.cartFull.items.splice(index,1);
          }
        }
      ]
    });
    alert.present();
  }

  cartTotal() {
    let total = 0;
    if (this.cartFull != null) {
      for (let x = 0; x < this.cartFull.items.length; x++) {
        total += parseFloat(this.cartFull.items[x].total);
      }
    }
    return total;
  }
  checkout() {
    let l = this.loadingCtrl.create();
    l.present();
    this.doctorService.cartFull = this.cartFull;
    this.doctorService.syncCart().subscribe((data:any) => {
      l.dismiss();
      this.navCtrl.push(ModalCheckout);
    });
    
  }
  ngOnDestroy(){
    /*this.renderer.removeClass(document.body.querySelector("ng-component.app-root"), 'blur');*/
  }


}

