function useError(options = {}) {
	options = lodash.merge(
		{
			test: false,
		},
		options,
	);

	const r = Vue.reactive({
		total: 0,
		message: false,
		fields: {},

		clear() {
			this.total = 0;
			this.message = false;
			this.fields = {};
		},

		get(field) {
			return this.fields[field] || [];
		},

		exists() {
			return this.fieldErrorsList(r.fields).length > 0 || r.message;
		},

		all() {
			return this.fieldErrorsList(r.fields);
		},

		fieldErrorsList(fields) {
			let arr = [];

			if (Array.isArray(fields)) {
				arr = [...fields];
			} else if (typeof fields == "object" && fields !== null) {
				for (const i in fields) {
					arr = [...arr, ...fields[i]];
				}
			}

			return arr;
		},

		setData(err) {
			this.clear();

			// If is axios request response error
			if (err.response) {
				if (err.response.data.message) {
					if (Array.isArray(err.response.data.message)) {
						this.message = err.response.data.message.join("\n");
					} else if (typeof err.response.data.message == "object") {
						this.message = err.message;
						this.fields = err.response.data.message;
					} else {
						this.message = err.response.data.message;
					}
				}
			}

			// if is pure exception error
			else {
				this.message = err.message;
			}

			this.total =
				r.fieldErrorsList(r.fields).length + (r.message ? 1 : 0);
		},
	});

	return r;
}

window.useError = useError;
