import { observable, action, computed } from 'mobx';

export default class Currency {
	@observable currencyList = [];
	@observable currencyId = "";
	@observable currencyData = {
	  	id : '',
		name : '',
		kurs: '',
		is_primary : ''
	};

	@observable isLoading = false;
	@observable isPrimarySet = false;	
	constructor(context) {
	    this.http = context.http;
	    this.context = context;
	}

	@action
	getAll(){
		this.isLoading = true;
		return this.http.get(`currencies`).then(res => {
			this.currencyList = res;
			// console.log(this.currencyList);
			this.isLoading = false;
		});
	}

	
	@action
	getById(id){
		this.currencyId = id;
		this.isLoading = true;
		return this.http.get(`currencies?id=${id}`).then(detail => {
			this.currencyData = detail[0];
			this.isLoading = false;
		})
	}

	@action
	getPrimary(){
		this.http.get(`currencies?is_primary=true`).then(res => {
			if(res.length == 0){
				this.isPrimarySet = false;
			}
			else{
				this.isPrimarySet = true;
			}
		})
	}


	@computed 
	get isEmpty(){
		if(this.currencyList.length > 0){
			return false;
		}
		return true;
	}

	@action
	post(){
		this.isLoading = true;
		this.http.post(`currencies`, this.currencyData).then(res => {
			this.isLoading = false;
			this.getAll();
			return res;
		});
		console.log(this.currencyData);
	}

	@action
	put(id){
		this.isLoading = true;
		this.http.put(`currencies/${id}`, this.currencyData).then(res => {
			this.isLoading = false;
			this.getAll();
			return res;
		});
	}

	@action
	del(id){
		this.isLoading = true;
		this.http.delete(`currencies/${id}`).then(res => {
			this.isLoading = false;
			this.getAll();
			return res;
		})
	}
}
