import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular';
import { CommonProvider } from '../../providers/common/common';
import { Storage } from '@ionic/storage';

import {TranslateService} from '@ngx-translate/core';
import { SubjectService } from '../../providers/subject.service';
import { WebService_lang } from '../../providers/web.service';
import * as $ from 'jquery';
declare var google;



@IonicPage()
@Component({
  selector: 'page-service',
  templateUrl: 'service.html',
})
export class ServicePage {
  @ViewChild('language') language: ElementRef;
	lang =  'en';

	result:any;
	selected_service:any;
	price:any;
	user_id:any;
	myDate:any;
	myTime:any;
  response:any;
  time_list:any;
  service_state:boolean = true;
  user:any;
  current_date = new Date().toISOString(); 

  constructor(
    public translate: TranslateService,
    public subjectService: SubjectService,
    public service_lang: WebService_lang,
    public navCtrl: NavController,
     public navParams: NavParams,
      public service: CommonProvider,
      public storage: Storage,
      public modalCtrl: ModalController,
      ) {
  	this.result = navParams.get('shop');
    //console.log(this.result);
    //var work_time = this.result.shop.working_time;
    //var work_time = '9:30AM-10:00PM';
    this.time_list = this.get_hours(this.result.shop.working_time);

  	console.log(this.result);
  	this.selected_service = [];
  	//this.user_id = 1;
    this.storage.get('user_data').then(data => {
      console.log(data);
      if(data){
        this.user_id = data.id;
      }
      
    })
     //this.storage.set('user_data', response.profile);
    this.price = 0;

    
    this.subjectService.getLangData().subscribe(langData => {
      console.log(langData);
      this.lang = this.service_lang.getLocalStorageItem('lang');
      console.log(this.lang);
      if (this.lang) {
        translate.setDefaultLang(this.lang);
        translate.use(this.lang);
      }
    });

    
    const lang  = this.service_lang.getLocalStorageItem('lang');
    console.log(lang);

    if(lang !== undefined){
      this.lang = lang;
    }

    if(this.lang === 'ru') {
      $('body').addClass('ru');
    } else {
      $('body').removeClass('ru');
    }

   // this.lang = 'en';

    translate.setDefaultLang(this.lang);

    // the lang to use, if the lang isn't available, it will use the current loader to get them

    translate.use(this.lang);
  }



  ionViewDidLoad() {
    console.log('ionViewDidLoad ServicePage');
    this.storage.get('user_data').then(data => {
      console.log(data);
      if(data){
        this.user = data;
      }
      
    })
  }

  call_time(){
    console.log('called'); 

    var d1 = new Date();
    var d = d1.getDate();
    var m = d1.getMonth()+1;
    var y = d1.getFullYear();
    var sec_date = y+"-"+m+"-"+d;
    console.log(this.myDate);
    console.log(sec_date);
    var d3 = new Date(sec_date);
    console.log(d3);




    var d2 = new Date(this.myDate);
    this.myTime = '';
    //var work_time = "9.30AM-7.00PM";
    var work_time = this.result.shop.working_time;

    if(+d3 === +d2){
      d1.setHours(d1.getHours() + 1);
      this.time_list = this.get_hours(work_time,true);
    } else {
      this.time_list = this.get_hours(work_time,false);
    }




    
  }




  



  get_hours(work_time=null,state=false){
    console.log(work_time);
    var today = new Date();
    today.setHours(today.getHours() + 1);
    var h = today.getHours();
    //work_time = "9.30AM-7.00PM";
    var res = work_time.split("-");
    var first_time;
    var second_time;

    var substring = "PM";
    console.log(res[0]);

    if(res[0].indexOf(substring)>0){
      var start = res[0].split(":");
      first_time = parseInt(start[0])+12;
      console.log(first_time);
      var first_res = start[1].replace("PM", "");
    } else {
      start = res[0].split(":");
      console.log(start);
      first_time = parseInt(start[0]);
      var first_res = start[1].replace("AM", "");
      console.log(first_time);
    }

    if(res[1].indexOf(substring)>0){
      var end = res[1].split(":");
      second_time = parseInt(end[0])+12;
      var second_res = end[1].replace("PM", "");
      console.log(second_time);
    } else {
      var end = res[1].split(":");
      second_time = parseInt(end[0]);
      var second_res = end[1].replace("AM", "");
      console.log(second_time);
    }

    console.log(this.myDate);


    var time_string = [];
    if(first_time<second_time){
      if(first_res!=='00'){
        first_time = parseInt(first_time)+1;
      }

      
      if(state==true){
        if(first_time<h){
          if(second_time<h){
            first_time = second_time = 0;
          } else {
            first_time = h;
          }
        } 
      }

      

      for(var i = first_time;i<=second_time;i++){
        time_string.push(i);
      }
    }

    if(second_time<first_time){
      if(second_res!=='00'){
        second_time = parseInt(second_time)+1;
      }

      if(state==true){
        if(second_time<h){
          if(first_time<h){
            second_time = first_time = 0;
          } else {
            second_time = h;
          }
        } 
      }


      for(var i = second_time;i<=first_time;i++){
        time_string.push(i);
      }
    }

    var time_loop = time_string.join();

    console.log(time_loop);

    if(time_loop=='0'){
      this.service_state = false;
    } else {
      this.service_state = true;  
    }
    return time_loop;

  }

  service_choose(service,event){
  	if(event.checked==true){
      this.selected_service.push(service.id);
      this.price = parseInt(this.price)+parseInt(service.price);
    } else {
      var index = this.selected_service.indexOf(service.id);
      this.price = parseInt(this.price)-parseInt(service.price);
      this.selected_service.splice(index,1);
    } 
  }

  done(){
    this.service.show_loader();
    if(this.service_state==false){
      this.service.presentToast("All Booking of service has been Closed today");
      return false;
    }
    if(this.user!=null){
      var myTime = this.tConvert(this.myTime);
    	var post_data = {
    					"booking_id":"VMIG"+this.user.id+this.result.shop.id,
    					"user_id":this.user.id,
    					"shop_id":this.result.shop.id,
    					"booking_date":this.myDate,
    					"booking_time":myTime,
    					"total":this.price,
    					"status":"Request",
    					"service":this.selected_service
    					};
              console.log(post_data);
    	this.service.post_data('booking',post_data).subscribe(data=>{
        console.log('console data'+data);
        if(data == '1'){
          this.service.presentToast("Sorry, This time is not Available");
          return false;
        }else{
          this.response = {"booking_date":this.myDate,"booking_time":myTime,"booked_id":data};

          this.navCtrl.push('SuccessPage',{'shop':this.response});
        }

    		//console.log(data);
    	})
    } else {
      console.log("not logged")
      let profileModal = this.modalCtrl.create("SignupmodalPage");
       profileModal.onDidDismiss(data => {
         this.user = data;
       })
       profileModal.present();
    }

  }

  back(){
    this.navCtrl.pop();
  }

  tConvert (time) {
    time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

    if (time.length > 1) { // If time format correct
      time = time.slice (1);  // Remove full string match value
      time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
      time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    return time.join (''); // return adjusted time or original string
  }

  check_time(){
    if(this.myTime!=''){
      var select_time = this.myTime;
      var time = select_time.split(":");
      if(parseInt(time[0])>12){
        var df = time[0] < 12 ? ' AM' : ' PM';
        time[0] = parseInt(time[0]) - 12;
        this.myTime = time[0]+":"+parseInt(time[1])+df;
        console.log(this.myTime);
      }
    } 
  }

  check_validate(){
    //console.log(this.myDate,this.myTime);
    if(this.myDate!=undefined && this.myTime!=''){
      return false;
    } else {
      return true;
    }
  }

  	 

}
