
import { check, PERMISSIONS, RESULTS, request, openSettings } from 'react-native-permissions';
import { Platform, Alert } from 'react-native';
import i18n from '~/locale/i18n';

import { PERMISSION_REQUEST } from '~/store/constants';

const storageAccessDialog = ({ isBlocked = false, permissionCode }) => new Promise((resolve, reject) => {
	const title = i18n.t(`permission.${Platform.OS}.download.title`);
	const description = i18n.t(`permission.${Platform.OS}.download.description`);
	const descriptionBlocked = i18n.t(`permission.${Platform.OS}.download.descriptionBlocked`);
	const goToSettings = i18n.t(`permission.${Platform.OS}.goToSettings`);
	const allowAccess = i18n.t(`permission.${Platform.OS}.allowAccess`);
	try {
		Alert.alert(
			title,
			(isBlocked) ? descriptionBlocked : description,
			[
				{
					text: i18n.t('common.cancel'),
					style: 'cancel',
					onPress: () => resolve(PERMISSION_REQUEST.CANCELLED),
				},
				{
					text: (isBlocked) ? goToSettings : allowAccess,
					style: 'default',
					onPress: () => {
						if (isBlocked) {
							openSettings()
								.then(() => resolve(PERMISSION_REQUEST.SETTINGS_OPENED))
								.catch(() => reject(Error('Cant open Settings')));
						} else {
							request(permissionCode)
								.then((result) => {
									// console.log(result);
									if (result === RESULTS.GRANTED) resolve(PERMISSION_REQUEST.GRANTED);
									else resolve(PERMISSION_REQUEST.DENIED);
								})
								.catch((e) => {
									reject(e);
								});
						}
					},
				},
			],
			{ cancelable: false },
		);
	} catch (e) {
		reject(e);
	}
});

export const askForStorageAccess = () => new Promise(async (resolve, reject) => {
	let permissionCode;
	try {
		if (Platform.OS === 'ios') {
			permissionCode = PERMISSIONS.IOS.PHOTO_LIBRARY;
		} else {
			permissionCode = PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE;
		}
		const permissionStatus = await check(permissionCode);
		switch (permissionStatus) {
			case RESULTS.UNAVAILABLE:
				reject(Error('Permission Unavailable'));
				break;
			case RESULTS.DENIED: {
				const response = await storageAccessDialog({ permissionCode });
				resolve(response);
				break;
			}
			case RESULTS.GRANTED:
				resolve(PERMISSION_REQUEST.GRANTED);
				break;
			case RESULTS.BLOCKED: {
				const response = await storageAccessDialog({ permissionCode, isBlocked: true });
				resolve(response); // opened settings
				break;
			}
			default:
		}
	} catch (e) {
		reject(e);
	}
	reject(Error('Unknown Error'));
});

