import { Model } from 'dva';
import { changeName } from './service';
import { message } from 'antd';

export interface AccountModelState {
  nameEditable: boolean;
  nameInput: string;
  nameSubmitting: boolean;
}

const model: Model = {
  namespace: 'account',

  state: {
    nameEditable: false,
    nameInput: '',
    nameSubmitting: false,
  } as AccountModelState,

  effects: {
    *changeName(_, { put, all, call, select }) {
      const { nameInput } = yield select((state: any) => state.account);
      if (!nameInput) return;

      yield put({ type: 'onUpdateState', nameSubmitting: true });
      try {
        yield call(changeName, nameInput);
        yield all([
          put({ type: 'onUpdateState', nameInput: '', nameEditable: false }),
          put({ type: 'user/updateUser', payload: { nickname: nameInput } }),
        ]);
      } catch (e) {
        message.error(e.message);
      } finally {
        yield put({ type: 'onUpdateState', nameSubmitting: false });
      }
    },
  },

  reducers: {
    onUpdateState(state, payload) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default model;
