/**
 * 获取位置权限处理
 * @邠心vbe on 2023/02/15
 */
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { check, openSettings, PERMISSIONS, request, RESULTS } from 'react-native-permissions';
import Button from '../../../components/Button';

//global.hasPermission = false;

/**
 * 检查是否有定位权限
 * @param {function} back callback(hasPermission, canRequestPermission)
 */
const checkPermission = (back) => {
  check(
      isIOS 
    ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
    : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION)
  .then(res => {
    console.log('[LocationPermission] checkPermission', res);
    switch (res) {
      case RESULTS.UNAVAILABLE:
        console.log('此功能不可用（在此设备上/在此上下文中）');
        if (isIOS) {
          back(true, true);
        } else {
          back(false, true);
        }
        break;
      case RESULTS.DENIED:
        console.log('权限未被请求/被拒绝，但可以请求');
        back(false, true);
        break;
      case RESULTS.LIMITED:
        console.log('权限是有限的：有些操作是可能的');
        back(true, true);
        break;
      case RESULTS.GRANTED:
        console.log('许可被授予');
        back(true, true);
        break;
      case RESULTS.BLOCKED:
        console.log('权限被拒绝，不再可请求');
        back(false, false);
        /*Dialog.showDialog({
          title: 'Error',
          message: 'Can not get charge station, Please grant location permissions.',
          ok: 'SETTING',
          callback: btn => {
            if (btn == Dialog.BUTTON_OK) {
              console.log('ok');
              openSettings().catch(() => console.warn('cannot open settings'));
            }
          }
        });*/
        break;
    }
  }).catch(erros => {
    console.log('[LocationPermission] checkPermission-catch', erros);
    back(false, false);
  });
}

/**
 * 请求定位权限
 * @param {function} back callback(hasPermission)
 */
const getPermission = (back) => {
  request(
      isIOS 
    ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
    : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION)
  .then(res => {
    console.log('[LocationPermission] requestPermission', res);
    back(res == RESULTS.GRANTED);
  }).catch(erros => {
    console.info('[LocationPermission] requestPermission-catch', erros)
    back(false);
  });
}

const LocationPermission = ({visible=false}) => (
  visible
  ? <View style={styles.permissionView}>
      <Text
        style={styles.permissionText}
        numberOfLines={1}>{$t("home.locationPermissionTips")}</Text>
      <Button
        style={styles.viewButton}
        viewStyle={styles.viewButtonStyle}
        onClick={() => openSettings().catch(() => console.warn('cannot open settings'))}>
        <Text style={styles.buttonText}>{$t("nav.view")}</Text>
        <FontAwesome
          size={16}
          color={colorPrimary}
          name='angle-right'/>
      </Button>
    </View>
  : <></>
);

const styles = StyleSheet.create({
  permissionView: {
    //top: 80,
    left: 16,
    right: 16,
    bottom: 32,
    opacity: .8,
    overflow: 'hidden',
    borderRadius: 30,
    position: 'absolute',
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: '#FEB751'
  },
  permissionText: {
    flex: 1,
    color: textDark,
    fontSize: 11,
    paddingLeft: 16,
    paddingRight: 2
  },
  viewButton: {
    borderRadius: 0,
    backgroundColor: 'transparent'
  },
  viewButtonStyle: {
    alignItems: 'center',
    flexDirection: 'row',
    ...$padding(8, 12, 8, 8),
  },
  buttonText: {
    color: colorPrimary,
    fontSize: 11,
    paddingRight: 4
  }
})

export default {
  VIEW: LocationPermission,
  checkPermission: checkPermission,
  requestPermission: getPermission
}
