import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { UserService } from '../user.service';
import { XeroService } from '../xero.service';
import { Owner } from '../owner.model';
import { Observable } from 'rxjs';

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

var Buffer = require('buffer/').Buffer;

function sleep(ms:number) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function redirect(r: Router) {
        await sleep(2000);
		r.navigate(['/shop']);
}

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

export class XeroRegComponent implements OnInit {
	public owner:Owner = {
		_id: '',
		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: ''
	};
	public ownerUpdate:Observable<Owner>;
	public flag: boolean = false;
	// -------------------------------------
	//
	// Language Support
	//
	vE = {
		xeroConnecting2xero : '',
		xeroConnected2xero : '',
	}	
	//
	constructor(
		private languageService : LanguageService,
		public xeroService: XeroService,
		public userService: UserService,
		private router: Router,
		private activatedRoute: ActivatedRoute
	) {
		this.ownerUpdate = userService.ownerUpdate;
		this.ownerUpdate.subscribe((owner) => {
			this.owner = owner;
		});
		this.userService.findUser();
	}

	ngOnInit(): void {
		this.chgUILanguage();
	}

	ngAfterViewInit(): void {
		this.ownerUpdate.subscribe((owner) => {
			this.owner = owner;
			this.activatedRoute.queryParams.subscribe((params) => {
				//console.log(params);
				if (params.state === this.owner.address.substring(0,6)) {
					this.xeroService.getXeroAccessToken(params.code, this.owner.address).subscribe(tokenData => {
						if (tokenData.status == 200) {
							//console.log(tokenData.body!);
							this.flag = true;
							redirect(this.router);
						} else {
							//console.log('Error: '+tokenData.status);
							this.flag = false;
						}
					});
				} else {
					console.log('Error: State mismatch');
				}
			});

		});
	}

	chgUILanguage(){
	  //console.log('XERO.chgUILanguage Called ');
		this.languageService.getViewElements('xero').subscribe({
			next: 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.xeroConnecting2xero = response.data.xero_connecting_2xero;
				this.vE.xeroConnected2xero = response.data.xero_connected_2xero;

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

}
