import { IFolderTree, IImage, IImageFolder } from "@ax/types";
import {
	SET_DATA,
	SET_IS_LOADING,
	SET_IS_SAVING,
	SET_IS_UPLOADING,
	SET_UPLOAD_SUCCESS,
	SET_UPLOAD_ERROR,
	SET_SELECTED_TAB,
	SET_DISPLAY_MODE,
	SET_CURRENT_FOLDER_CONTENT,
	SET_CURRENT_FOLDER,
	SET_BREADCRUMB,
	SET_FOLDERS_TREE,
} from "./constants";
import { GalleryActionsCreators } from "./interfaces";

export interface IData {
	items: IImage[];
	page: number;
	isFinished: boolean;
}

export interface IIsLoading {
	init: boolean;
	more: boolean;
}

export interface IIsSaving {
	save: boolean;
	saveAdd: boolean;
	delete: boolean;
}

export interface IGalleryState {
	data: IData;
	isLoading: IIsLoading;
	isSaving: IIsSaving;
	isUploading: boolean;
	isSuccess: boolean;
	isError: boolean;
	errorMsg: string;
	currentFolderContent: IImageFolder | null;
	currentFolderID: number | null;
	breadcrumb: IFolderTree[];
	foldersTree: IFolderTree[];
	displayMode: "grid" | "list";
	selectedTab: "site" | "global";
}

export const initialState: IGalleryState = {
	data: {
		items: [],
		page: 1,
		isFinished: false,
	},
	isLoading: {
		init: false,
		more: false,
	},
	isSaving: {
		save: false,
		saveAdd: false,
		delete: false,
	},
	isUploading: false,
	isSuccess: false,
	isError: false,
	errorMsg: "",
	currentFolderContent: null,
	currentFolderID: null,
	breadcrumb: [],
	foldersTree: [],
	displayMode: "grid",
	selectedTab: "site",
};

export function reducer(state = initialState, action: GalleryActionsCreators): IGalleryState {
	switch (action.type) {
		case SET_DATA:
		case SET_IS_LOADING:
		case SET_IS_SAVING:
		case SET_IS_UPLOADING:
		case SET_UPLOAD_SUCCESS:
		case SET_UPLOAD_ERROR:
		case SET_DISPLAY_MODE:
		case SET_SELECTED_TAB:
		case SET_CURRENT_FOLDER_CONTENT:
		case SET_CURRENT_FOLDER:
		case SET_BREADCRUMB:
		case SET_FOLDERS_TREE:
			return { ...state, ...action.payload };
		default:
			return state;
	}
}

export { initialState as galleryInitialState, reducer as galleryReducer };
