import AsyncStorage from '@react-native-community/async-storage';
import Restart from './Restart';
import Modal from '../components/Modal';

const onPressQr = async value => {
  if (!value) {
    await AsyncStorage.removeItem('QRHOST');
  } else {
    await AsyncStorage.setItem('QRHOST', value);
  }
  Restart.restartApp();
};

const onPressEnv = async value => {
  if (!value) {
    await AsyncStorage.removeItem('HOST');
  } else {
    await AsyncStorage.setItem('HOST', value);
  }
  Restart.restartApp();
};

export const switchQr = async () => {
  const host = await AsyncStorage.getItem('QRHOST');
  Modal.prompt(
    null,
    '切换二维码地址',
    [
      {
        text: '取消',
      },
      {
        text: '确认',
        onPress: onPressQr,
      },
    ],
    'default',
    host,
    ['输入二维码地址'],
  );
};

export const switchEnv = async () => {
  const host = await AsyncStorage.getItem('HOST');
  Modal.prompt(
    null,
    '切换服务器地址',
    [
      {
        text: '取消',
      },
      {
        text: '确认',
        onPress: onPressEnv,
      },
    ],
    'default',
    host,
    ['输入服务器地址'],
  );
};

window.host = onPressEnv;
window.qrcode = onPressQr;

export default {switchQr, switchEnv};
