import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {Validators, FormBuilder, FormGroup, FormControl,FormArray } from '@angular/forms';
import { Storage } from '@ionic/storage';
import {Myservice} from '../../providers/myservice';

@IonicPage()
@Component({
  selector: 'page-offered',
  templateUrl: 'offered.html',
})
export class OfferedPage {

	todo = {}
	services_offered:any;
	selected_services:any;
	nonselected_services:any;
	user_data:any;
	myForm: FormGroup;
	 

	constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, public storage: Storage, private myservice: Myservice) {
		this.storage.get('user_data').then((user_data) => {
				if(user_data){
					this.user_data=user_data
					this.get_selected_services();
					 
					 
				}
		})
		this.get_services()
		
		this.myForm = formBuilder.group({
			services: this.formBuilder.array([])
		})  

	}
	

	ionViewDidLoad() {
		console.log('ionViewDidLoad OfferedPage');
	}

	back(){
		this.navCtrl.pop();
	}
	timing(){
		this.navCtrl.push('TimingPage')
	}
	
	get_services(){
		this.myservice.show_loader();
		this.myservice.load_get('get_services').subscribe(data => {
			this.myservice.hide_loader();
			if(data.status == 'success'){
				this.services_offered = data.result;
				
					 
				console.log(this.services_offered)
			}
		});
	}
	
		get_selected_services(){
		this.myservice.show_loader();
		this.myservice.load_get('get_selected_services/id/'+this.user_data.id).subscribe(data => {
			this.myservice.hide_loader();
			if(data.status == 'success'){
				this.selected_services = data.result;
				 
			}
		});
	}
	 
	
	
	updateCheckedOptions(serv, isChecked: boolean) {
      console.log(serv)
      const services = <FormArray>this.myForm.controls.services;
      if(isChecked) {
        services.push(new FormControl(serv));
      } else {
        let index = services.controls.findIndex(x => x.value.id == serv.id);
        services.removeAt(index);
      }
	}

	
	logForm(form){
		 
		 var arr=[];
		 for (var i = 0; i < form.services.length; i++) { 
			 console.log(form.services[i])
			 arr[i]={ 'garage_id' :this.user_data.id , 'service_id' : form.services[i].id };
			 
		}
		this.myservice.show_loader();
		this.myservice.load_post({arr},'add_services').subscribe(data => {
			this.myservice.hide_loader();
			if(data.status == 'success'){
				this.navCtrl.push('Services')	
			}
			else{
				this.myservice.show_alert("Error", data.message);
			}
		});
		 
	}
}
