import { Component, OnInit, ChangeDetectorRef, ViewChild, AfterViewInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { MatDialog, MatDialogConfig} from '@angular/material/dialog';
import { UntypedFormBuilder, Validators, UntypedFormGroup } from '@angular/forms';
import { ProgressBarMode } from '@angular/material/progress-bar';
import { MatStepper } from '@angular/material/stepper';
import { UserService } from '../user.service';
import { FullnodeService } from '../fullnode.service';
import { ScanComponent} from '../scan/scan.component';
import { Tx } from '../tx.model';
import { User } from '../user.model';
import { Owner } from '../owner.model';
import { Subscription, Observable } from 'rxjs';
import { v4 as uuidv4 } from 'uuid';

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

@Component({
	selector: 'app-login',
	templateUrl: './login.component.html',
	styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit, AfterViewInit {
	txs: Tx[] = [];
	intervalHolder: any;
	nodeAddress: string = '';
	localToken: string | null = '';
	selectedValue: number = 0.001;
	pinError: boolean = false;
	public user:User = {
		address: '',
		session: '',
		blocktime: 0,
		pin: '',
		validated: false
	};
	public owner:Owner = {
		address: '',
		name: '',
		currency: '',
		tax: false,
		taxValue:0,
		vat: false,
		vatValue: 0,
		paid: false,
		zats: false,
		invoices: false,
		expiration: new Date(Date.now()).toISOString(),
		payconf: false,
		crmToken: ''
	};
	private FullnodeSub: Subscription = new Subscription();
	private UserSub: Subscription = new Subscription();
	public heightUpdate: Observable<number>;
	public uZaddrUpdate: Observable<string>;
	public userUpdate: Observable<User>;
	public ownerUpdate: Observable<Owner>;
	//public txsUpdate: Observable<Tx[]>;
	prompt: boolean = false;
	confirmedMemo: boolean = false;
	targetBlock: number = 0;
	barMode: ProgressBarMode = 'indeterminate';
	barValue = 0;
	barMessage = 'Scanning blockchain for login memo, please wait.';
	@ViewChild('stepper') private myStepper?: MatStepper;

	pinForm: UntypedFormGroup;

    //
    // Language Support
    //
    vE = {
    	loginConfirmLogin : '',
    	loginConnectToZGo : '',
    	loginEnterPin : '',
    	loginLastBlock : '',
    	loginLinkWallet : '',
		loginCheckWallet : '',
		loginWrongPin : '',
		loginConfirmPin : ''
    }
    //
    // ------------------------------------------------------------
	constructor(
		private fb: UntypedFormBuilder,
		private activatedRoute: ActivatedRoute,
		public fullnodeService: FullnodeService,
		private router: Router,
		public userService: UserService,
		private dialog: MatDialog,
		private _changeDetectorRef: ChangeDetectorRef,
		private languageService: LanguageService
	){

		//this.fullnodeService.getAddr();
		this.pinForm = fb.group({
			pinValue: [null, Validators.required]
		});
		this.heightUpdate = fullnodeService.heightUpdate;
		this.uZaddrUpdate = userService.uZaddrUpdate;
		this.userUpdate = userService.userUpdate;
		this.ownerUpdate = userService.ownerUpdate;
		this.userUpdate.subscribe((user) => {
			this.user = user;
		});
		this.ownerUpdate.subscribe((owner) => {
			this.owner = owner;
		});
		//this.txsUpdate = userService.txUpdate;
		//this.txsUpdate.subscribe((txs) => {
			//this.txs = txs;
		//});
	}

	ngAfterViewInit(){

		//console.log('Step', this.myStepper);
		this.pinError = false;
		//console.log('Activated route data in Component:::', this.activatedRoute.data);
		this.activatedRoute.data.subscribe((addrData) => {
			//console.log('FETCH ADDRESS', addrData);
			this.nodeAddress = addrData.response.addr;
			//console.log('Node addres ', this.nodeAddress);
			this.localToken = localStorage.getItem('s4z_token');
			//console.log(localToken);
			if(this.localToken == null){
				var token = uuidv4();
				localStorage.setItem('s4z_token', token);
				this.localToken = token;
			}
			this.loginCheck();
		});
	}

	ngOnInit(){
        this.chgUILanguage();
		this.intervalHolder = setInterval(() => {
			this.fullnodeService.getHeight();
			this.loginCheck();
			this._changeDetectorRef.markForCheck();
		}, 1000 * 60);
	}

	loginCheck(){
		this.userService.checkUser()!.subscribe({
			next: (checkResponse) => {
				if (checkResponse.status == 200) {
					console.log('checkUser true');
					if(this.myStepper!.selectedIndex === 0) {
						this.myStepper!.next();
						this.myStepper!.next();
					} else {
						if(this.myStepper!.selectedIndex === 1){
							this.myStepper!.next();
						}
					}
					if(checkResponse.body!.validated) {
						console.log('redirecting to biz');
						this.userService.getOwner();
						this.router.navigate(['/biz']);
						clearInterval(this.intervalHolder);
					} else {
						console.log('validated failed');
					}
				}
			},
			error: (error) => {console.log(error);}
		});
	}

	login(stepper: MatStepper) {
		//console.log('Dropdown:', this.entryForm.value.selectedSession);
		const dialogConfig = new MatDialogConfig();

		dialogConfig.disableClose = true;
		dialogConfig.autoFocus = true;
		dialogConfig.data = {
			totalZec: 1e-8,
			addr: this.nodeAddress,
			session: this.localToken,
			pay: false
		};

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

	confirmPin(){
		this.userService.validateUser(this.pinForm.value.pinValue).subscribe((val) => {
			if (val) {
				this.router.navigate(['/biz']);
				clearInterval(this.intervalHolder);
			} else {
				this.pinError = true;
			}
		});
	}

	ngOnDestroy(){
		this.FullnodeSub.unsubscribe();
		this.UserSub.unsubscribe();
		clearInterval(this.intervalHolder);
	}

	chgUILanguage(){
        //console.log('LOGIN.chgUILanguage Called ');
 		this.languageService.getViewElements('login').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.loginLastBlock = response.data.login_last_block;
			        this.vE.loginConnectToZGo = response.data.login_connect_to_zgo;
			        this.vE.loginLinkWallet = response.data.login_link_wallet;
			        this.vE.loginConfirmLogin = response.data.login_confirm_login;
			        this.vE.loginEnterPin = response.data.login_enter_pin;
			        this.vE.loginCheckWallet = response.data.login_check_wallet;
			        this.vE.loginWrongPin = response.data.login_wrong_pin;
			        this.vE.loginConfirmPin = response.data.login_confirm_pin;
			    },
				error  => { console.log('Error >> ',error); }
			);
	}
}
