import {Component, OnInit } from '@angular/core';
import { NavController, NavParams, LoadingController, AlertController, ToastController, ModalController } from 'ionic-angular';

import { environment } from "../../environments/environment"
import {SocialSharing} from "@ionic-native/social-sharing";
import * as moment from 'moment';
import { DoctorService } from '../../services/doctor.service';
import { Pata } from '../../pata';
import { ModalCart } from '../../modals/cart/cart';
import { UserService } from '../../services/user.service';
@Component({
  selector: 'page-producto',
  templateUrl: 'producto.html'
})
export class ProductoPage implements OnInit{

  public image = '';
  public link = '';
  id: string = '';
  private isSharing: boolean;
  public loaded: boolean = false;
  public product: any = null;
  public loading: any = null;
  public cartItems: number = 0;
  public item: any = {quantity: null};
  public pkg5:number = null;
  public pkg8:number = null;
  public balance: number = 0;
  public limits: boolean = false;
  public user: any = { id: '0' };

  constructor(public navCtrl: NavController,
              private navParams: NavParams,
              private socialSharing: SocialSharing,
              public loadingCtrl: LoadingController,
              public modalCtrl: ModalController,
              public service: Pata,
              public alertCtrl: AlertController,
              public toastCtrl: ToastController,
              public userService: UserService,
              public doctorService: DoctorService)
  {

    let loading = this.loadingCtrl.create();
    loading.present();
    this.id = this.navParams.get("id");
    this.userService.getProfile().subscribe((result:any)=>{
      this.user = result;
    });
    this.doctorService.getProduct(this.id).subscribe((data:any) => {    
      this.product = data.data;

      let max_order = parseFloat(this.product.max_order);
      let min_order = parseFloat(this.product.min_order);

      if (min_order > 0 || max_order > 0) {
        this.limits = true;
      }
      this.loaded = true;
      loading.dismiss();
    });
    this.doctorService.getBalanceGrow().subscribe((data:any) => {
      this.balance = data.balance;
    });
    this.doctorService.getCart().subscribe((data:any)=> {
      this.cartItems = data.short.length;
    });      
  }

  ngOnInit(){
    
  }
  comprar() {
    let max_order = parseFloat(this.product.max_order);
    let min_order = parseFloat(this.product.min_order);

    if (min_order == 0) {
      min_order = 1;
    }
    if (max_order == 0) {
      max_order = 999999999;
    }

    if (this.product.type_sale == 'FLOR') {
      this.item.quantity = ( ( (this.pkg5 ? this.pkg5 : 0) * 5 ) + ( (this.pkg8 ? this.pkg8 : 0) * 8 ) );
    }

    if (this.item.quantity < min_order) {
      let toast = this.toastCtrl.create({
        message: 'Cantidad debe ser '+min_order+' o más',
        duration: 3000,
        position: 'bottom'
      });   
      toast.onDidDismiss(() => { });
      toast.present();
    } 
    else if (this.item.quantity > max_order) {
      let toast = this.toastCtrl.create({
        message: 'Cantidad debe ser '+max_order+' o menos',
        duration: 3000,
        position: 'bottom'
      });   
      toast.onDidDismiss(() => { });
      toast.present();
    }     
    else {
      let add = this.doctorService.addCartItem({
        id: this.product.id,
        stock: this.stock(),
        qty: this.item.quantity,
        price: parseFloat(this.product.price),
        total: ((this.item.quantity) * parseFloat(this.product.price))
      });
      if (add) {
        this.service.showOk("Producto agregado con éxito");
        this.item.quantity = null;
        this.cartItems = this.doctorService.cartFull.items.length;
        this.pkg5 = null;
        this.pkg8 = null;
        this.doctorService.syncCart();
      } else {
        let toast = this.toastCtrl.create({
          message: 'La cantidad de tu carro supera el stock (Max: '+this.stock()+')',
          duration: 3000,
          position: 'bottom'
        });   
        toast.onDidDismiss(() => { });
        toast.present();
      }
    }
  }
  ionViewDidEnter(){

  }
  stock() {
    let s = parseInt(this.product.stock_sale) || 0;
    return s;
  }
  add() {
    this.item.quantity++;
  }
  rem() {
    this.item.quantity--;
    if (this.item.quantity < 0) {
      this.item.quantity = 0;
    }
  }
  cart() {
    let cartModal = this.modalCtrl.create(ModalCart);
    cartModal.onDidDismiss((data:any) => {
      if (data) {
        this.cartItems = data.items.length;
        this.doctorService.cartFull = data;
        this.doctorService.syncCart();
        if (data.hasOwnProperty("finish") && data.finish == 1) {
          this.service.showOk(data.msg);
        }
      }
    });
    cartModal.present();
  }
  dateformat(fecha){
    var fecha_mm = moment(fecha);
    return moment(fecha_mm.format(),moment.ISO_8601).format();
  }

}
