import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable }  from 'rxjs';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Order } from './order/order.model';
import { Owner } from './owner.model';
import { UserService } from './user.service';

import { ConfigData } from './configdata';

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

@Injectable({
  providedIn: 'root'
})
export class ReceiptService {
	beUrl = ConfigData.Be_URL;
	private dataStore: {order: Order, owner: Owner } = {
		owner: {
			_id: '',
			name: '',
			address: '',
			currency: 'usd',
			tax: false,
			taxValue: 0,
			vat: false,
			vatValue: 0,
			paid: false,
			zats: false,
			invoices: false,
			expiration: new Date(Date.now()).toISOString(),
			payconf: false,
			crmToken: ''
		},
		order: {
			address: '',
			session: '',
			timestamp: '',
			closed: false,
			currency: '',
			price: 0,
			total: 0,
			totalZec: 0,
			paid: false,
			externalInvoice: '',
			shortCode: '',
			lines: [
				{
					qty: 1,
					name: '',
					cost:0
				}
			]
		}
	};
	private _orderUpdated: BehaviorSubject<Order> = new BehaviorSubject(this.dataStore.order);
	public readonly orderUpdate: Observable<Order> = this._orderUpdated.asObservable();
	public _nameUpdated: BehaviorSubject<string> = new BehaviorSubject(this.dataStore.owner.name);
	public readonly nameUpdate: Observable<string>= this._nameUpdated.asObservable();
	public readonly ownerUpdate;
	private reqHeaders: HttpHeaders;
	private session: null|string;
	private params: HttpParams;

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

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

		obs.subscribe((OrderDataResponse) => {
			if (OrderDataResponse.status == 200) {
				this.dataStore.order = OrderDataResponse.body!.order;
				this._orderUpdated.next(Object.assign({}, this.dataStore).order);
				this.userService.getOwner();
				this.ownerUpdate.subscribe((owner) => {
					this.dataStore.owner = owner;
					this._nameUpdated.next(Object.assign({}, this.dataStore).owner.name);
				});
			} else {
				this._orderUpdated.next(Object.assign({}, this.dataStore).order);
				console.log('No order found');
			}
		});

		return obs;
	}

}
