import _ from 'lodash';
import validate from 'validate.js';

export * from './preset';

const EMAIL_REGEX = /^(([^<>()\]\\.,;:\s@"]+(\.[^<>()\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const MOBILE_REGEX = /^\+\d{12}/;

validate.validators.not = (value, options, attribute, attributes) => {
	const { validator, ...otherOptions } = options;
	const error = validate.validators[validator](value, otherOptions, attribute, attributes);
	if (error === undefined) {
		if (options.message) {
			return options.message;
		}
		return 'not valid';
	}
	return undefined;
};

// validate.validators.multiple = (value, options, attribute, attributes) => {
// 	const { validator, constrains } = options;
// 	const errors = [];
// 	constrains.forEach((c, index) => {
// 		const error = validate.validators[validator](value, c, attribute, attributes);
// 		if (error) {
// 			if (c.message) {
// 				errors.push(c.message);
// 				return;
// 			}
// 			errors.push(`not valid for constrain ${index}`);
// 		}
// 	});
// 	return errors.length ? errors : undefined;
// };

const trimString = (str) => _.invoke(str, 'trim', str);

export const validator = (values, constrains = {}, numOfErrors = 1) => {
	if (!values) return undefined;
	const errors = validate(values, { ...constrains }, { fullMessages: false });
	if (!errors) return errors;
	const result = {};
	Object.keys(errors).forEach(k => {
		result[k] = errors[k].slice(0, numOfErrors);
	});
	return result;
};

export const emailFormat = (email) => {
	const trimmedEmail = trimString(email);
	let formatted = '';
	if (EMAIL_REGEX.test(trimmedEmail)) {
		formatted = trimmedEmail;
	}
	return formatted;
};

export const isValidEmail = (email) => {
	let status = false;
	const trimmedEmail = trimString(email);
	if (email.indexOf('@') > 1 && trimmedEmail.split('@').length <= 2) {
		const formattedEmail = emailFormat(trimmedEmail);
		status = (EMAIL_REGEX.test(formattedEmail));
	}
	return status;
};

export const isValidMobile = (mobile) => {
	const trimmedMobile = trimString(mobile);
	const status = (MOBILE_REGEX.test(trimmedMobile));
	return status;
};

export const nameFormat = (name) => {
	let formmatted = name.replace(/(\s{1,})/g, ' '); // replace all space
	formmatted = formmatted.replace(/\s*/, ''); // infix
	formmatted = formmatted.replace(/\s*$/, ''); // suffix
	return formmatted;
};

export const isValidVideo = (type) => (type !== undefined && (type === 'video/mp4' || type === 'video' || type === 'video/quicktime'));

