import {
	observable,
	action,
} from 'mobx';
import {
	WeaForm
} from 'comsMobx';

export default class FormStore {
	constructor(api) {
		this.api = api;
	}

	@observable form = new WeaForm();
	@observable loading = false;

	@action fetchForm = (params = {}) => {
		this.loading = true;

		return this.api.fetchForm(params).then(datas => {
			const conditions = this.getCondition(datas);

			this.form.setCondition(conditions);
			this.loading = false;
		})
	}

	validateForm = (form) => {
		return new Promise( (resolve,reject) => {
			form.validateForm().then(f => {
				if (f.isValid) {
					resolve(true);
				} else {
					f.showErrors();
					resolve(false);
				}
			})
		})
	}

	getCondition=(datas)=>{
		let c = [];
		Object.keys(datas).forEach(key=>{
			if (key.includes('condition')) {
				c = datas[key];
			}
		})
		return c;
	}
}