import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { LicenseCardIssuesState } from "./state";
import { createCardLicenseAsync } from "./operations";

const initialState: LicenseCardIssuesState = {
  apps: {
    numberOfCreateLicenses: 0,
    isLoading: false,
  },
};
export const licenseCardSlice = createSlice({
  name: "licenseCard",
  initialState,
  reducers: {
    changeNumberOfCreateLicenses: (
      state,
      action: PayloadAction<{ numberOfCreateLicenses: number }>
    ) => {
      const { numberOfCreateLicenses } = action.payload;
      state.apps.numberOfCreateLicenses = numberOfCreateLicenses;
    },
    cleanupApps: (state) => {
      state.apps = initialState.apps;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(createCardLicenseAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(createCardLicenseAsync.fulfilled, (state, action) => {
      // csvファイルダウンロード処理
      // ファイル名は「{発行日時}_licenseCard.csv」とする
      const currentDate = new Date();
      const currentDateString = currentDate
        .toISOString()
        .replace(/[^0-9]/g, "")
        .slice(0, -3);
      const filename = `${currentDateString}_licenseCard.csv`;

      const blob = new Blob([action.payload.cardLicenseKeys.toString()], {
        type: "mime",
      });
      const blobURL = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = blobURL;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      a.parentNode?.removeChild(a);
      state.apps.isLoading = false;
    });
    builder.addCase(createCardLicenseAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
  },
});

export const { changeNumberOfCreateLicenses, cleanupApps } =
  licenseCardSlice.actions;

export default licenseCardSlice.reducer;
