import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable }  from 'rxjs';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

import { ConfigData } from './configdata';

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

@Injectable({
  providedIn: 'root'
})
export class XeroService {
	beUrl = ConfigData.Be_URL;
	clientId: string = '';
	//clientSecret: string = '';
	xeroToken: any = {
		accessToken: '',
		refreshToken: '',
		expiresIn: 0,
		scope: '',
		tokenType: ''
	};
	xeroAcc: string = '';
	savedAcc : boolean = false;

	public savedAccObs = new Observable((observer) => {
     console.log("starting savedAccObs");
     setTimeout(() => {observer.next(this.savedAcc)},1000);
	})

	private _clientIdUpdated: BehaviorSubject<string> = new BehaviorSubject(this.clientId);
	//private _clientSecretUpdated: BehaviorSubject<string> = new BehaviorSubject(this.clientSecret);
	private _tokenUpdated: BehaviorSubject<any> = new BehaviorSubject(this.xeroToken);
	private _accCodeUpdated: BehaviorSubject<string> = new BehaviorSubject(this.xeroAcc);
	public readonly clientIdUpdate: Observable<string> = this._clientIdUpdated.asObservable();
	//public readonly clientSecretUpdate: Observable<string> = this._clientSecretUpdated.asObservable();
	public readonly tokenUpdate: Observable<any> = this._tokenUpdated.asObservable();
	public readonly accCodeUpdate: Observable<string> = this._accCodeUpdated.asObservable();
	private reqHeaders: HttpHeaders;
	private reqParams: HttpParams;
	private session: null | string;

	constructor(
		private http: HttpClient
	) {
		var auth = 'Basic ' + Buffer.from(ConfigData.UsrPwd).toString('base64');
		this.reqHeaders = new HttpHeaders().set('Authorization', auth);
		this.session = localStorage.getItem('s4z_token');
		this.reqParams = new HttpParams().append('session', this.session!);
		this.getXeroConfig();
	}

	getXeroConfig(){
		let obs = this.http.get<{message: string, xeroConfig: any}>(this.beUrl+'api/xero', { headers:this.reqHeaders, observe: 'response', params: this.reqParams});

		obs.subscribe(xeroDataResponse => {
			if (xeroDataResponse.status == 200) {
				this.clientId = xeroDataResponse.body!.xeroConfig.clientId;
				//this.clientSecret = xeroDataResponse.body!.xeroConfig.clientSecret;
				this._clientIdUpdated.next(Object.assign({}, this).clientId);
				//this._clientSecretUpdated.next(Object.assign({}, this).clientSecret);
			} else {
				console.log('No config in DB!');
			}
		});
		
		return obs;
	}

	getXeroAccessToken(code: string, address: string){
		const params = this.reqParams.append('code', code).append('address', address);
		let obs = this.http.get(this.beUrl + 'api/xerotoken' , {headers: this.reqHeaders, params: params, observe: 'response'});
		return obs;
	}

	getXeroAccountCode(address: string){
		const params = this.reqParams.append('address', address);
		let obs = this.http.get<{message: string, code: string}>(this.beUrl + 'api/xeroaccount', {headers: this.reqHeaders, params: params, observe: 'response'});
		obs.subscribe(accountResponse => {
			if (accountResponse.status == 200) {
				this.xeroAcc = accountResponse.body!.code;
				this._accCodeUpdated.next(Object.assign({}, this).xeroAcc);
			} else {
				console.log('No account in DB');
			}
		});
		return obs;
	}

	setXeroAccountCode(address: string, code: string) {

		const params = this.reqParams.append('address', address).append('code', code);
		let obs = this.http.post(this.beUrl + 'api/xeroaccount', {}, {headers: this.reqHeaders, params: params, observe: 'response'});
/*
		obs.subscribe(responseData => {
			if (responseData.status == 202) {
				console.log('Account saved');
        this.savedAcc = true; 
			} 
		}, error => {
			this.savedAcc = false;
			console.log("error : " + error.msg)
		});
*/
		return obs;
	}
}
