/**
 * Created by rockyl on 2019-09-19.
 */
import {projectApi} from "../../api";

export const projectsStore = {
	state: {
		projectCount: 0,
		projects: [],
	},
	mutations: {
		updateProjects(state, {projects, projectCount}) {
			state.projects.splice(0);
			state.projects.push(...projects);

			state.projectCount = projectCount;
		},
		addProject(state, project) {
			state.projects.unshift(project);
		},
		deleteProject(state, projectID) {
			const {projects} = state;

			for (let i = 0, li = projects.length; i < li; i++) {
				const item = projects[i];

				if (item.id === projectID) {
					projects.splice(i, 1);
					break;
				}
			}
		},
	},
	actions: {
		async fetchProjects({commit, state}, {keyword, currentPage, pageSize, onlyMine}) {
			const data = await projectApi.fetchAll(keyword, currentPage, pageSize, onlyMine);
			commit('updateProjects', data);
		},
		async fetchProject({commit}, projectId) {
			return await projectApi.fetchOne(projectId);
		},
		async fetchHistory({commit}, {projectID, currentPage, pageSize}) {
			return await projectApi.fetchHistory(projectID, currentPage, pageSize);
		},
		async createProject({commit}, data) {
			const project = await projectApi.createOne(data);
			commit('addProject', project);
			return project;
		},
		async duplicateProject({commit}, data) {
			const project = await projectApi.duplicateOne(data);
			commit('addProject', project);
			return project;
		},
		async deleteProject({commit}, projectID) {
			await projectApi.deleteOne(projectID);
			commit('deleteProject', projectID);
			return projectID;
		},
	},
};