import React from 'react';
import { View, Text } from 'react-native';
import { Toast } from 'antd-mobile';
import { errors as errorCodes } from './config';
import navigator from '../services/navigator';


const { navigate } = navigator;

const errStyle = {
  overflow: 'auto',
  wordWrap: 'break-word',
  width: '360px',
  height: '360px',
  marginLeft: '-24px',
  marginTop: '24px',
};

export function processError(err) {
  if (err) {
    if (err.preventDefault) {
      err.preventDefault();
    }
    if (err.data) {
      const { data } = err;
      switch (data.errorCode) {
        case errorCodes.no_such_user:
          Toast.fail('用户不存在！');
          break;
        case errorCodes.invalid_token:
          navigate('Login');
          break;
        default:
          showError(err);
      }
    }
  }
}

function showError(err) {
  if (err) {
    let msg;
    if (err.data) {
      const { data } = err;
      msg = data ? data.message : err.message;
    } else {
      msg = err.message;
    }
    if (msg && msg.length < 256) {
      Toast.fail(msg);
    } else {
      navigate('Error', {
        title: '服务器内部错误',
        content: <Text>{ msg }</Text>,
      });
    }
  }
}

export function createError({ code, msg }) {
  const error = new Error(msg);
  error.data = {
    errorCode: code,
    message: msg,
  };
  return error;
}

export const errors = {
  tokenMissing: () => createError({
    code: errorCodes.token_missing,
    msg: '需要登录！',
  }),
  wrongPassword: () => createError({
    code: errorCodes.wrong_password,
    msg: '密码错误！',
  }),
  unsupportedAuthType: (...types) => createError({
    code: errorCodes.unsupported_auth_type,
    msg: `不支持的客户端验证方式：${types.join('、')}.`,
  }),
};
