import { Item } from './item.model';
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 ItemService{

	beUrl = ConfigData.Be_URL;
	

	private dataStore: { items: Item[] } = { items: [] } ;
	private _itemsUpdated: BehaviorSubject<Item[]> = new BehaviorSubject(this.dataStore.items);
	public readonly itemsUpdated: Observable<Item[]> = this._itemsUpdated.asObservable();
	private address:string = '';
	private reqHeaders: HttpHeaders;
	private session: null|string;
	private params: HttpParams;

	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.params = new HttpParams().append('session', this.session!);
	}

	getItems(addr: string){
		this.address = addr;
		const newParams = this.params.append('address', addr);
		let obs = this.http.get<{message: string, items: any}>(this.beUrl+'api/items', { headers:this.reqHeaders, params: newParams, observe: 'response'});

		obs.subscribe((ItemDataResponse) => {
			if (ItemDataResponse.status == 200 ) {
				this.dataStore.items = ItemDataResponse.body!.items;
				this._itemsUpdated.next(Object.assign({},this.dataStore).items);
			} else {
				this.dataStore.items = [];
				this._itemsUpdated.next(Object.assign({},this.dataStore).items);
			}
		});

		return obs;
	}

	addItem(item: Item) {
		let obs = this.http.post<{message: string}>(this.beUrl+'api/item', { payload: item }, { headers: this.reqHeaders, params: this.params });

		obs.subscribe(() => {
			this.getItems(this.address);
		});

		return obs;
	}

	deleteItem(id: string) {
		let obs = this.http.delete<{message: string}>(this.beUrl+'api/item/'+id, { headers: this.reqHeaders, params: this.params });

		obs.subscribe(() => {
			this.getItems(this.address);
		});

		return obs;
	}
}
