import { Component, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators, UntypedFormGroup } from '@angular/forms';
import { MatDialog, MatDialogConfig} from '@angular/material/dialog';
import { ProgressBarMode } from '@angular/material/progress-bar';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { MatStepper } from '@angular/material/stepper';
import { MatSlideToggleChange } from '@angular/material/slide-toggle';
import { Country } from '../country.model';
import { Owner } from '../owner.model';
import { User } from '../user.model';
import { UserService } from '../user.service';
import { FullnodeService } from '../fullnode.service';
import { ScanComponent } from '../scan/scan.component';
import { TermsComponent } from '../terms/terms.component';

import { LanguageService } from '../language.service';

@Component({
  selector: 'app-business',
  templateUrl: './business.component.html',
  styleUrls: ['./business.component.css']
})
export class BusinessComponent implements OnInit {
	
	@ViewChild('stepper', { static: false}) stepper: MatStepper|undefined;
	intervalHolder: any;
	nodeAddress: string = '';
	zecPrice: number = 1;
	tickets = [
		{
			value: 1,
			viewValue: '1 day: USD $1'
		},{
			value: 6,
			viewValue: '1 week: USD $6'
		},{
			value: 22,
			viewValue: '1 month: USD $22'
		},{
			value: 30,
			viewValue: '1 month Pro: USD $30'
		}
	];
	bizForm: UntypedFormGroup;
	payForm: UntypedFormGroup;
	barMessage = 'Awaiting for transaction';
	barMode: ProgressBarMode = 'indeterminate';
	barValue = 0;
	countries: Country[] = [];
	owner: Owner = {
			address: '',
			name: '',
			currency: 'usd',
			tax: false,
			taxValue: 0,
			vat: false,
			vatValue: 0,
			paid: false,
			zats: false,
			invoices: false,
			expiration: new Date(Date.now()).toISOString(),
			payconf: false,
			crmToken: ''
		}
	public countriesUpdate: Observable<Country[]>;
	public ownerUpdate: Observable<Owner>;
	public addrUpdate: Observable<string>;
	public userUpdate: Observable<User>;
	public priceUpdate: Observable<number>;
	sessionId = '';
	ownerKnown = false;
	termsChecked = false;
	ownerdata = {
			first: '',
			last: '',
			phone: '',
			name: '',
			street: '',
			city: '',
			state: '',
			postal: '',
			country: '',
			email: '',
			website: ''
	};
	// -------------------------------------
  //
  // Language Support
  //
	vE = {
		businessSignupTitle : '',
		businessBizInfo : '',
		businessAddrsNobiz : '',
		businessBizNamelbl : '',
		businessBizNameholder : '',
		businessContactFnamelbl : '',
		businessContactFnholder : '',
		businessContactLnamelbl : '',
		businessContactLnholder : '',
		businessBizAddresslbl : '',
		businessBizAddressholder : '',
		businessBizCitylbl : '',
		businessBizCityholder : '',
		businessBizStatelbl : '',
		businessBizStateholder : '',
		businessBizPcodelbl : '',
		businessBizPcodeholder : '',
		businessBizCountrylbl : '',
		businessBizCountryholder : '',
		businessBizMaillbl : '',
		businessBizMailholder : '',
		businessBizWebsitelbl : '',
		businessBizWebsiteholder : '',
		businessAcceptTerms : '',
		businessTermsOfuse : '',
		businessSaveBtn : '',
		businessSessionLengthlbl : '',
		businessSelectSession : '',
		businessSessionLabel : '',
		businessSessionPaylbl : '',
		businessZGoConfirmlbl : ''

	};
	//
  //
	constructor(
		private languageService : LanguageService,
		private fb: UntypedFormBuilder,
		private userService: UserService,
		private fullnodeService: FullnodeService,
		private dialog: MatDialog,
		private router: Router
	) {
		this.priceUpdate = fullnodeService.priceUpdate;
		this.priceUpdate.subscribe(priceInfo => {
			this.zecPrice = priceInfo;
		});
		this.countriesUpdate = userService.countriesUpdate;
		this.ownerUpdate = userService.ownerUpdate;
		this.userUpdate = userService.userUpdate;
		this.userUpdate.subscribe(userInfo => {
			this.sessionId = userInfo.session;
		});
		this.addrUpdate = fullnodeService.addrUpdate;
		this.addrUpdate.subscribe(nodeAdd => {
			this.nodeAddress = nodeAdd;
		});
		this.bizForm = fb.group({
			name: ['', Validators.required],
			first: ['', Validators.required],
			last: ['', Validators.required],
			street: ['', Validators.required],
			city: ['', Validators.required],
			state: ['', Validators.required],
			postal: ['', Validators.required],
			country: ['', Validators.required],
			email: ['', [Validators.email, Validators.required]],
			website: [''],
			terms: [false]
		});
		this.payForm= fb.group({
			session: ['', Validators.required]
		});
		this.userService.getCountries();
		this.countriesUpdate.subscribe((countries) => {
			this.countries = countries;
		});
		this.ownerUpdate.subscribe((owner) => {
			this.owner = owner;
		});
	}

	ngOnInit(): void {
		this.chgUILanguage();
		this.intervalHolder = setInterval(() => {
			this.loginCheck();
		}, 1000 * 60);
	}

	ngAfterViewInit(): void {
		this.ownerUpdate.subscribe(ownerData => {
			if(ownerData.name.length > 0 && this.stepper!.selectedIndex == 0){
				this.stepper!.next();
				this.loginCheck();
			}
		});
	}

	onChange(ob: MatSlideToggleChange){
		//console.log(ob.checked);
		this.termsChecked = ob.checked;
	}

	showTerms() {
		const dialogConfig = new MatDialogConfig();
		dialogConfig.disableClose = true;
		dialogConfig.autoFocus = true;

		this.dialog.open(TermsComponent, dialogConfig);
		//dialogRef.afterClosed().subscribe(val => {
			//console.log('Terms read');
		//});
	}

	save() {
		this.ownerdata = {
			first: this.bizForm.get('first')!.value,
			last: this.bizForm.get('last')!.value,
			phone: '',
			name: this.bizForm.get('name')!.value,
			street: this.bizForm.get('street')!.value,
			city: this.bizForm.get('city')!.value,
			state: this.bizForm.get('state')!.value,
			postal: this.bizForm.get('postal')!.value,
			country: this.bizForm.get('country')!.value,
			email: this.bizForm.get('email')!.value,
			website: this.bizForm.get('website')!.value
		};
		this.userService.addOwner(this.ownerdata);
		this.stepper!.next();
	}

	pay(){
		const dialogConfig = new MatDialogConfig();

		dialogConfig.disableClose = true;
		dialogConfig.autoFocus = true;
		dialogConfig.data = {
			totalZec: (this.payForm.get('session')!.value)/this.zecPrice,
			addr: this.nodeAddress,
			session: this.sessionId,
			pay: true
		};

		const dialogRef = this.dialog.open(ScanComponent, dialogConfig);
		dialogRef.afterClosed().subscribe(val => {
			//console.log('Awaiting payment');
			if(val){
				this.stepper!.next();
			}
		});
	}

	loginCheck(){
		this.userService.findUser();
		this.ownerUpdate.subscribe((owner) => {
			if(owner.paid) {
				clearInterval(this.intervalHolder);
				this.router.navigate(['/shop']);
			}
		});
	}

	chgUILanguage(){
		//console.log('BUSINESS.chgUILanguage Called ');
		this.languageService.getViewElements('business').subscribe(
			response => { 
				//console.log('Received >> ', response );
				//console.log('Language Code : ', response.language);
				//console.log('Component Name : ',response.component);
				//console.log('Language data : ',response.data);

				this.vE.businessSignupTitle = response.data.business_signup_title;
				this.vE.businessBizInfo = response.data.business_biz_info;
				this.vE.businessAddrsNobiz = response.data.business_addrs_nobiz;
				this.vE.businessBizNamelbl = response.data.business_biz_namelbl;
				this.vE.businessBizNameholder = response.data.business_biz_nameholder;
				this.vE.businessContactFnamelbl = response.data.business_contact_fnamelbl;
				this.vE.businessContactFnholder = response.data.business_contact_fnholder;
				this.vE.businessContactLnamelbl = response.data.business_contact_lnamelbl;
				this.vE.businessBizAddresslbl = response.data.business_biz_addresslbl;
				this.vE.businessBizAddressholder = response.data.business_biz_addressholder;
				this.vE.businessBizCitylbl = response.data.business_biz_citylbl;
				this.vE.businessBizCityholder = response.data.business_biz_cityholder;
				this.vE.businessBizStatelbl = response.data.business_biz_statelbl;
				this.vE.businessBizStateholder = response.data.business_biz_stateholder;
				this.vE.businessBizPcodelbl = response.data.business_biz_pcodelbl;
				this.vE.businessBizPcodeholder = response.data.business_biz_pcodeholder;
				this.vE.businessBizCitylbl = response.data.business_biz_citylbl;
				this.vE.businessBizCityholder = response.data.business_biz_cityholder;
				this.vE.businessBizCountrylbl = response.data.business_biz_countrylbl;
				this.vE.businessBizCountryholder = response.data.business_biz_countryholder;
				this.vE.businessBizMaillbl = response.data.business_biz_maillbl;
				this.vE.businessBizMailholder = response.data.business_biz_mailholder;
				this.vE.businessBizWebsitelbl = response.data.business_biz_websitelbl;
				this.vE.businessBizWebsiteholder = response.data.business_biz_websiteholder;
				this.vE.businessAcceptTerms = response.data.business_accept_terms;
				this.vE.businessTermsOfuse = response.data.business_terms_ofuse;
				this.vE.businessSaveBtn = response.data.business_save_btn;
				this.vE.businessSessionLengthlbl = response.data.business_session_lengthlbl;
				this.vE.businessSelectSession = response.data.business_select_session;
				this.vE.businessSessionLabel = response.data.business_session_label;
				this.vE.businessSessionPaylbl = response.data.business_session_paylbl;
				this.vE.businessZGoConfirmlbl = response.data.business_zgo_confirmlbl;

			    },
					error  => { console.log('Error >> ',error); }
			);
	}

}
