import store from '@/store/index';

function upsert(el, binding) {
	let display = '';

	switch (el.tagName) {
		case 'DIV':
			display = 'block';
			break;
		default:
			display = 'inline-block';
	}

	el.style.display = onPermission(binding.value) ? display : 'none';
}

function parse(value) {
	const permission = store.state.menu.permission;

	if (typeof value == 'string') {
		return value ? permission.some(e => e.includes(value.replace(/\s/g, ''))) : false;
	} else {
		return Boolean(value);
	}
}

export const PermissionDirective = {
	install(Vue) {
		Vue.directive('permission', {
			inserted: upsert,
			update: upsert
		});
	}
};

export const onPermission = value => {
	if (!value) {
		return false;
	}

	if (Object.prototype.toString.call(value) === '[object Object]') {
		if (value.or) {
			return value.or.some(parse);
		}

		if (value.and) {
			return value.and.find(e => !parse(e)) === undefined ? true : false;
		}
	}

	return parse(value);
};
