import {
  Actions,
  ActionType,
} from './totp.action';

import {
  State,
  initialState,
} from './totp.state';

export function reducer(state = initialState, action: Actions): State {
  switch (action.type) {
    case ActionType.CreateTotp: {
      return {
        ...state,
        error: null,
        pending: true,
      };
    }

    case ActionType.CreateTotpSuccess: {
      const secretKey = action.payload.key;
      const keyURI = action.payload.uri;
      return {
        ...state,
        totp: {key: secretKey, uri: keyURI},
        error: null,
        pending: false,
        secretKey: secretKey,
        keyURI: keyURI,
      };
    }

    case ActionType.CreateTotpFailure: {
      return {
        ...state,
        error: action.payload,
        pending: false,
        secretKey: null,
        keyURI: null,
      };
    }

    case ActionType.Regist: {
      return {
        ...state,
        error: null,
        pending: true,
      };
    }

    case ActionType.RegistSuccess: {
      return {
        ...state,
        error: null,
        pending: false,
      };
    }

    case ActionType.RegistFailure: {
      return {
        ...state,
        error: action.payload,
        pending: false,
      };
    }

    default: {
      return state;
    }
  }
}