import Actions from '@/types/Store/Actions';
import { BluetoothDevice } from '@/types/Shower/Shower';
import { UPDATE_BLUETOOTH_DEVICE } from './actions';
import Taro from '@tarojs/taro';

const storeKey = 'DeviceInfo';

let INITIAL_STATE = {
  code: '',
  isOnlyBluetooth: undefined,
  position: '',
};

try {
  var value = Taro.getStorageSync(storeKey);
  if (value) {
    INITIAL_STATE = value;
  }
} catch (e) {
  console.error(e);
}

export default function ShowerReducer(
  state: StoreState<BluetoothDevice> = INITIAL_STATE,
  actions: Actions,
) {
  switch (actions.type) {
    case UPDATE_BLUETOOTH_DEVICE:
      Taro.setStorage({
        key: storeKey,
        data: actions.payload,
      });
      return {
        ...state,
        ...actions.payload,
      };
    default:
      return state;
  }
}
