import { AppAction, AppState } from "./types";

export const initialAppState: AppState = {
  config: {
    strip_utms: true,
    fix_quotes: true,
    fix_newlines: true,
    play_sound: true,
    autostart: false,
    hotkey: "Alt+Shift+C",
    custom_params: [],
  },
  hotkeyConflict: false,
  hwid: "",
  isLicensed: false,
  tabState: { tab: "general", isRecording: false },
};

export function appReducer(state: AppState, action: AppAction): AppState {
  switch (action.type) {
    case "INITIALIZE":
      return {
        ...state,
        config: action.payload.config,
        hotkeyConflict: action.payload.hotkeyConflict,
        hwid: action.payload.hwid,
        isLicensed: action.payload.isLicensed,
        tabState: action.payload.isLicensed
          ? { tab: "general", isRecording: false }
          : { tab: "license", keyInput: "", isActivating: false, error: "" },
      };
    case "SET_TAB": {
      const nextTab = action.payload;

      if (!state.isLicensed && nextTab !== "license") {
        return state;
      }

      if (nextTab === "general") {
        return { ...state, tabState: { tab: "general", isRecording: false } };
      }

      if (nextTab === "rules") {
        return { ...state, tabState: { tab: "rules" } };
      }

      return {
        ...state,
        tabState: {
          tab: "license",
          keyInput: "",
          isActivating: false,
          error: "",
        },
      };
    }
    case "SET_CONFIG":
      return {
        ...state,
        config: { ...state.config, ...action.payload },
      };
    case "SET_RECORDING":
      if (state.tabState.tab === "general") {
        return {
          ...state,
          tabState: { ...state.tabState, isRecording: action.payload },
        };
      }

      return state;
    case "SET_LICENSE_KEY_INPUT":
      if (state.tabState.tab === "license") {
        return {
          ...state,
          tabState: { ...state.tabState, keyInput: action.payload, error: "" },
        };
      }

      return state;
    case "START_ACTIVATION":
      if (state.tabState.tab === "license") {
        return {
          ...state,
          tabState: { ...state.tabState, isActivating: true, error: "" },
        };
      }

      return state;
    case "ACTIVATION_SUCCESS":
      return {
        ...state,
        isLicensed: true,
        tabState: {
          tab: "license",
          keyInput: "",
          isActivating: false,
          error: "",
        },
      };
    case "ACTIVATION_FAILURE":
      if (state.tabState.tab === "license") {
        return {
          ...state,
          tabState: {
            ...state.tabState,
            isActivating: false,
            error: action.payload,
          },
        };
      }

      return state;
    case "SET_HOTKEY_CONFLICT":
      return { ...state, hotkeyConflict: action.payload };
    default:
      return state;
  }
}
