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

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 = {
		address: '',
		name: '',
		currency: '',
		tax: false,
		taxValue:0,
		vat: false,
		vatValue: 0,
		first: '',
		last: '',
		email: '',
		street: '',
		city: '',
		state: '',
		postal: '',
		phone: '',
		paid: false,
		website: '',
		country: '',
		zats: false,
		invoices: false,
		expiration: new Date(Date.now()).toISOString(),
		payconf: false,
		viewkey: '',
		crmToken: ''
	};
	public ownerUpdate:Observable<Owner>;
	public flag: boolean = false;



	constructor(
		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 {
	}

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

		});
	}

}
