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

@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: '',
			currency: 'usd',
			tax: false,
			taxValue: 0,
			vat: false,
			vatValue: 0,
			phone: '',
			paid: false,
			first: '',
			last: '',
			name: '',
			street: '',
			city: '',
			state: '',
			postal: '',
			country: '',
			email: '',
			website: '',
			zats: false,
			invoices: false,
			expiration: new Date(Date.now()).toISOString(),
			payconf: false,
			viewkey: '',
			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;

	constructor(
		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.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;

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

	save() {
		this.owner = {
			_id: '',
			address: '',
			currency: 'usd',
			tax: false,
			taxValue: 0,
			vat: false,
			vatValue: 0,
			first: this.bizForm.get('first')!.value,
			last: this.bizForm.get('last')!.value,
			phone: '',
			paid: false,
			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,
			zats: false,
			invoices: false,
			expiration: new Date(Date.now()).toISOString(),
			payconf: false,
			viewkey: '',
			crmToken: ''
		};
		this.userService.addOwner(this.owner);
		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']);
			}
		});
	}

}
