import { Component, OnInit, Input }             from '@angular/core'
import { FormControl, FormGroup, Validators }   from '@angular/forms'
import { Http}                                  from '@angular/http'

import { FormBase }                             from '@k-core/types/form-base'
import { payloadType }                          from '@k-core/types/payLoad'
import { FormService }                          from '@k-services/svc.form'
import { HelperService }                        from '@k-services/svc.helper'

@Component({
	moduleId: module.id+'',
	selector: 'dynamic-form',
	templateUrl: 'tpl.dynamic-form.pug',
	providers: [FormService]
})
export class DynamicFormComponent implements OnInit {

	// Vars
	// ------------------
	@Input('inputs') inputs: FormBase<any>[] = []
	@Input('action') action: string
	@Input('button') button: string
	@Input('buttonClasses') buttonClasses: string
	@Input('buttonPlacement') buttonPlacement: string
	@Input('customReceiver') customReceiver: payloadType
	form: FormGroup
	payLoad: payloadType
	submitAttempt = false
	submitted = false
	validArray = []
	posted: string

	constructor(
		private formService: FormService,
		private http: Http,
		private _helper: HelperService
	) { 
		this.setButtonClasses();
	}

	// TODO: Forms need to be updated to work with the model 
	// instead of working around it.


	// Events
	// ------------------
	ngOnInit() {
		this.form = this.formService.toFormGroup(this.inputs);
	}


	onSubmit() {
		console.log('onSubmit()');

		let containsError = false;

		console.log('this.validArray:');
		console.log(this.validArray);

		for(let input of this.validArray) {
			if(input.valid != true) {
				containsError = true;
			}
		}


		// If form is valid
		if(this.form.valid && !containsError) {

			// If identifier of a checkbox is "Newsletter", and it is ticked,
			// then sign up to newsletter
			if(!!this.form.value.newsletter) {
				this.signUpToNewsletter();
			}

			console.log('Form Submitted!');
			this.submitted = true;

			// Return message from server.
			this.payLoad = this.form.value;
			if(!!this.customReceiver) {
				this.payLoad.id = this.customReceiver.id
				this.payLoad.identifier = this.customReceiver.identifier
				console.log(this.payLoad)
			}

			let connector = ''

			if(this.action.slice(-1) !== '&') {
				connector = '&'
			}

			// Does a GET request to the server based on action + serialized payLoad
			this.http.get(this.action + connector + this.serialize(this.payLoad)).subscribe(
				response => {
					this.posted = response.json().data.message
				}
			)
		}
	}





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

	// Roundabout way to show required messages on submit
	attemptingSubmit() {
		console.log('attempting submit');
		this.submitAttempt = true;
	}


	/**
	 * Called on output from form-input.
	 * Add to or update validArray with inputName and Valid boolean
	 * @param payload - {key: string, valid: boolean}
	 */
	checkForInvalid(payload) {
		console.log('updating validArray')
		console.log(payload)

		console.log('validArray:')
		console.log(this.validArray)

		let index = -1;
		for(let i=0; i < this.validArray.length; i++) {
			if(this.validArray[i].key === payload.key) {
				index = i;
			}
		}

		console.log('index of key in validArray:')
		console.log(index)

		if(index >= 0) {
			this.validArray[index] = payload;
		}
		else {
			this.validArray.push(payload);
		}
	}


	// Creates serialized GET string of inputs
	serialize = function(obj: any, prefix?: any) {
		let str = [], p, serialize;

		for(p in obj) {
			if (obj.hasOwnProperty(p)) {
			var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
			str.push((v !== null && typeof v === "object") ?
				serialize(v, k) :
				encodeURIComponent(k) + "=" + encodeURIComponent(v));
			}
		}

		return str.join("&");
	}



	/**
	 * Sign up to newsletter when called
	 */
	signUpToNewsletter() {
		 let payLoad = {
			Country: '',
			FirstName1: '',
			LastName1: '',
			email: '',
			Title: '',
			Company: '',
			CustomerType: '',
			id: '',
			identifier: ''
		};

		payLoad.Country = this.form.value.country
		payLoad.FirstName1 = this.form.value.firstName
		payLoad.LastName1 = this.form.value.lastName
		payLoad.email = this.form.value.email
		payLoad.Title = this.form.value.title
		payLoad.Company = ( !!this.form.value.company ? this.form.value.company : '' )
		payLoad.CustomerType = this.form.value.consumer


		this.http.get(this._helper.server + '/feed/set/signup' + this._helper.credentials + '&check=1&' + this.serialize(payLoad)).subscribe(response => {
			console.log(response.json().data)
		})
	}
	

	/**
	 * Set defualt classes if none are supplied
	 */
	setButtonClasses(){
		if(!this.buttonClasses) {
			this.buttonClasses = 'mod--primary'
		}
	}
	

}