import { Component, Input, OnInit, Output, EventEmitter }     from '@angular/core'
import { FormGroup }    from '@angular/forms'

import { FormBase }		from '@k-core/types/form-base'
import {storeId} 		from '@k-settings/store-helper'


@Component({
	moduleId: module.id+'',
	selector: 'form-input',
	templateUrl: './tpl.form-input.pug',
	styleUrls: ['sty.form-input.scss']
})
export class FormInputComponent  implements OnInit {

	// Vars
	// -------------------
	@Input() input: FormBase<any>
	@Input() form: FormGroup
	@Input() submitAttempt: boolean

	@Output() isInputValid = new EventEmitter<any>()

	floatActive 		= false
	invalid 			= false
	focus 				= false
	errorMsg 			= ''
	requiredMsg 		= 'The field is required'

	selectKey 			= ''
	selectValue 		= ''
	checked: boolean 	= false
	inputCheck: any 	= 0





	// Events
	// -------------------

	ngOnInit() {

		// Set value for terms checkbox
		if(this.input.type === 'terms' || this.input.type == 'checkbox') {

			this.input.value = 0
			this.patchGroupValue(this.input.identifier, this.input.value)
		}


		// Handle select setup
		if(this.input.type === 'select') {
			this._handleSelect()
		}
	}






	// Functions
	// -------------------


	// Toggle float label if value is not empty
	toggleFloat(value) {

		if(!!value.length) {
			this.floatActive = true;
		}
		else {
			this.floatActive = false;
		}
	}


	// Simple focus toggle
	focusChange(focus) {
		this.focus = focus ? focus : !this.focus;
	}

	
	// Patch FormGroup with supplied value
	patchGroupValue(key, value){
		console.log(value)

		this.form.patchValue({[key]: value});
	}



	/** TODO: describe this function...
	 * 
	 * @param identifier 
	 */
	updateCheck(identifier) {
		if(!this.inputCheck) {
			this.inputCheck = 1
			this.checked = true
		} else {
			this.inputCheck = 0
			this.checked = false
		}

		this.patchGroupValue(identifier, this.inputCheck)
	}




	/**
	 * Set selected option to first option on load
	 */
	private _handleSelect() {
		let key     = this.input.key;
		let optKey  = this.input.options[0].key;
		let set     = false

		console.log(this.input)



		// Pre-select US value or sort alphabetically
		// TODO: Make this into a different country list in back-end
		// if(parseInt(storeId) === 2) {
		// 	if(this.input.identifier === 'country') {
		// 		for(let option of this.input.options) {
		// 			if(option.value === 'United States of America') {
		// 				this.form.controls[this.input.identifier].setValue(option.value, {OnlySelf: true})
		// 				this.selectValue = option.value;
		// 				set = true // raise flag so first value is not selected later
		// 			}
		// 		}
		// 	}
		// } else if(parseInt(storeId) === 1) {
		// 	if(this.input.identifier === 'country') {
		// 		this.input.options.sort((a,b) => {
		// 			if(a.value < b.value) return -1
		// 			if(a.value > b.value) return 1
		// 			return 0
		// 		})
		// 	}
		// }


		// Iterate over options and set selected for previously selected option
		// or set selected for first value if none has been set.
		// for(let option of this.input.options) {

		// 	if(option.selected) {
		// 		this.form.controls[this.input.identifier].setValue(option.value, {OnlySelf: true})

		// 		this.selectValue = option.value

		// 	} 
		// 	// 'country' select field is "undefined" as opposed to "true/false"
		// 	// this allows us to mark the first value of country as 'selected'
		// 	else if(typeof option.selected === 'undefined' && !set) {

		// 		console.log('option not selected - Selecting first option')
		// 		console.log(this.input.identifier)
		// 		console.log(option.value)
				
		// 		this.form.controls[this.input.identifier].setValue(option.value, {OnlySelf: true})
		// 		set = true

		// 		this.selectValue = option.value
		// 	}
			
		// }

		// this.patchGroupValue(key, optKey);






		// Sort alphabetically
		if(this.input.identifier === 'country') {
			this.input.options.sort((a,b) => {
				if(a.value < b.value) return -1
				if(a.value > b.value) return 1
				return 0
			})
		}


		// Add current select to invalidArray
		this.validateSelect(this.input.identifier, false);
	}


	/**
	 *  Validate select based either on given validity or rules
	 * @param inputKey 
	 * @param validity 
	 */
	validateSelect(inputKey: string, validity? : boolean) {
		let isValid = true

		if(typeof validity !== 'undefined') {
			isValid = validity;
		}

		// If not required, select is valid
		// no matter what previous validity var says
		if(!this.input.required) {
			isValid = true;
		}

		// Check if selected
		if(!!this.selectKey.length) {
			isValid = true;
		}

		// Set validity for input
		//this.invalid = !isValid; // There is currently no error message for select

		// Send output with valid state
		this.isInputValid.emit({'key': inputKey, 'valid': isValid});
	}







	// TODO: This probably needs to be updated. 
	// It seems there are bits missing eg. for handling checked and possible 4th param.

	/**
	 * Iterates over rules for given input and flags as invalid if a rule is broken.
	 * Emits valid/invalid status output and then resets
	 * 
	 * @param inputName - name of the input in question
	 * @param inputKey - identifier 
	 * @param inputChecked - Used ????
	 */
	checkValid(inputName: string, inputKey, inputChecked) {

		let isInvalid = false;
		let rules:any = (!!this.input.validation ? this.input.validation : false );
		let group = this.form;
		let value = group.get(inputKey).value;

		console.log(group);

		console.log('value');
		console.log(value);



		if(!!this.input.required && !!!value) {
			isInvalid = true;
			this.errorMsg = 'The input is required';
		}

		if(rules) {
			rules.forEach(rule => {
				
				switch(rule.type) {
					case 'minlength':
						if(value.length < rule.value && rule.value != '0') {
							isInvalid = true;
							this.errorMsg = rule.errorMessage;
						}
						break;
					case 'maxlength':
						if(value.length > rule.value && rule.value != '0') {
							isInvalid = true;
							this.errorMsg = rule.errorMessage;
						}
						break;
					case 'regex':
						let regex = new RegExp(rule.value)

						if(!value.match(regex)) {
							isInvalid = true;
							this.errorMsg = rule.errorMessage;
						}
						break;
				}

				console.log('type: ' + rule.type);
				console.log('rule value: ' + rule.value);
			});
		}

		console.log(inputName)

		// output valid status
		this.isInputValid.emit({'key': inputName, 'valid': !isInvalid});

		// Set valid vars
		this.invalid = isInvalid
		return isInvalid;
	}


	get isValid() { return this.form.controls[this.input.identifier].valid; }
}