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';

/**
 * Generated class for the RequestPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

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

	private requestsForm : FormGroup;
	service:any;
	filtr:any;
	arr:any=[];
	checkbox_val = [{'value': 'fuelfilter','name' : 'Fuel Filter'},{'value': 'cabinfilter','name' : 'Cabin Filter'},{'value': 'airfilter','name' : 'Air Filter'}]
	
	constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder,public storage:Storage, private myservice: Myservice,) {
		this.service = this.navParams.get('service')
		
	
		
		this.requestsForm = this.formBuilder.group({ 
			
			//filters: [{'value': 'fuelfilter','name' : 'Fuel Filter'}, ],
			km: ['', Validators.compose([Validators.required, Validators.maxLength(8)])],
			message: ['', Validators.required],
			filters: this.formBuilder.array([]),
		});
		 
		this.arr = [{'value': 'fuelfilter','name' : 'Fuel Filter'}]
		//this.requestsForm.controls['filters'].setValue({'value': 'fuelfilter','name' : 'Fuel Filter'});
		// if(this.service == 'Oil Service')
		//	 this.requestsForm.setControl('filters',new FormControl('',Validators.required));
		// else
		//	 this.requestsForm.setControl('filters',new FormControl('',));
	}

	ionViewDidLoad() {
		console.log('ionViewDidLoad RequestPage');
	}
	back(){
		this.navCtrl.pop()
	}
	
	onSubmit(){
		
		if(this.requestsForm.valid){
			console.log('in',this.requestsForm.value)
		}else{ // Form is not valid
			this.markFormGroupTouched(this.requestsForm);
		}
	}
	
	change_val(val,isChecked){
		console.log(val)
		const emailFormArray = <FormArray>this.requestsForm.controls.filters;

  if(isChecked) {
    emailFormArray.push(new FormControl(val));
  } else { 
    let index = emailFormArray.controls.findIndex(x => x.value.value == val.value)
    emailFormArray.removeAt(index);
  }
		 
		 
		// this.filtr = val
		// console.log(this.arr)
		// if(evt == true){
			// let index = this.arr.findIndex(x => console.log(x));
		// }
		// this.requestsForm.controls['filters'].setValue(this.arr);
		
				// console.log(this.arr)
				// console.log(index)
				// this.arr.splice(index, 1); 
		// console.log('val', val)
		// console.log('evt',evt)
	}
	
	/**** function to mark fields as touched ****/
	private markFormGroupTouched(formGroup: FormGroup) {
		(<any>Object).values(formGroup.controls).forEach(control => {
			control.markAsTouched();
			if (control.controls) {
				control.controls.forEach(c => this.markFormGroupTouched(c));
			}
		});
	}

}
