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 WoocommerceService {
	beUrl = ConfigData.Be_URL;
	private reqHeaders: HttpHeaders;
	private reqParams: HttpParams;
	private ownerId: string = '';
	private token: string = '';
	private siteurl: string = '';
	private session: null | string;
	private _ownerIdUpdated: BehaviorSubject<string> = new BehaviorSubject(this.ownerId);
	private _tokenUpdated: BehaviorSubject<string> = new BehaviorSubject(this.token);
	private _siteurlUpdated: BehaviorSubject<string> = new BehaviorSubject(this.siteurl);
	public readonly ownerUpdate: Observable<string> = this._ownerIdUpdated.asObservable();
	public readonly tokenUpdate: Observable<string> = this._tokenUpdated.asObservable();
	public readonly siteurlUpdate: Observable<string> = this._siteurlUpdated.asObservable();

	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._ownerIdUpdated.next(Object.assign({}, this).ownerId);
		this._tokenUpdated.next(Object.assign({}, this).token);
		this._siteurlUpdated.next(Object.assign({}, this).siteurl);
	}

	getWooToken(ownerId: string) {
		const params = this.reqParams.append('ownerid', ownerId);
		let obs = this.http.get<{ownerid: string, token: string, siteurl: string}>(this.beUrl + 'api/wootoken', {headers: this.reqHeaders, params: params, observe: 'response'});
		obs.subscribe(tokenResponse => {
			if (tokenResponse.status == 200) {
				this.ownerId = tokenResponse.body!.ownerid;
				this.token = tokenResponse.body!.token;
				this.siteurl = tokenResponse.body!.siteurl;
				this._ownerIdUpdated.next(Object.assign({}, this).ownerId);
				this._tokenUpdated.next(Object.assign({}, this).token);
				this._siteurlUpdated.next(Object.assign({}, this).siteurl);
			} else {
				console.log('No WooCommerce token found');
			}
		});
		return obs;
	}

	createWooToken(ownerId: string) {
		const params = this.reqParams.append('ownerid', ownerId);
		let obs = this.http.post(this.beUrl+'api/wootoken', {}, {headers: this.reqHeaders, params: params, observe: 'response'});
		obs.subscribe(responseData => {
			if (responseData.status == 202) {
				console.log('WooToken created.');
			} else {
				console.log('WooToken creation failed.');
			}
		});
		return obs;
	}
}
