import _ from 'lodash';

export const createUUID = () => {
	function chr4() {
		return Math.random().toString(16).slice(-4);
	}
	return `${chr4()}${chr4()}-${chr4()}-${chr4()}-${chr4()}-${chr4()}${chr4()}${chr4()}`;
};

export const jsonToURLEncoded = (element, parentKey, list = []) => {
	if (typeof (element) === 'object') {
		Object.keys(element).forEach((key) => {
			jsonToURLEncoded(element[key], parentKey ? `${parentKey}[${_.isArray(element) ? '' : key}]` : key, list);
		});
	} else {
		list.push(`${parentKey}=${encodeURIComponent(element)}`);
	}
	return list.join('&');
};

export const handleRequestData = (contentType, data) => {
	switch (contentType) {
		case 'application/x-www-form-urlencoded':
			return jsonToURLEncoded(data);
		default:
			return JSON.stringify(data);
	}
};

const orientationMap = {
	1: { rotation: 0, flip: false },
	2: { rotation: 0, flip: true },
	3: { rotation: 180, flip: false },
	4: { rotation: 180, flip: true },
	5: { rotation: 90, flip: true },
	6: { rotation: 90, flip: false },
	7: { rotation: 270, flip: true },
	8: { rotation: 270, flip: false },
};

export const orientationToRotation = (orientation) => (
	orientationMap[orientation] ? orientationMap[orientation] : orientationMap[1]
);
export const rotationToOrientation = (rotation, flip = false) => {
	let orientation = 1;
	Object.entries(orientationMap).forEach(([key, value]) => {
		if (value.rotation === rotation && value.flip === flip) {
			orientation = Number(key);
		}
	});
	return orientation;
};

export const mediaName = {
	dropbox: 'Dropbox',
	google: 'Google Photos',
};

// Given an image URL the following function will return just the s3key
export const getS3keyFromUrl = (url) => {
	const myRegexp = /([0-9]+\/[0-9]+_.*)\?/g;
	const match = myRegexp.exec(url);
	if (_.size(match) > 0) {
		return match[1]
			.replace('_PREVIEW', '')
			.replace('_MICRO_THUMBNAIL', '');
	}
	return url;
};

export const getS3keyFromFilename = (fileName) => {
	const regEx = /\.[^/.]+$/g;
	let result = fileName;
	while (_.size(regEx.exec(result)) > 0) {
		result = result.replace(regEx, '');
	}
	return result;
};

export const replaceS3keyProfileId = (s3Key, userProfileId) => {
	if (!s3Key || !userProfileId) {
		return s3Key;
	}
	const regEx = /[\d]+\/[\d]*/g;
	return s3Key.replace(regEx, `${userProfileId}/${userProfileId}`);
};
