/* eslint-disable @typescript-eslint/no-unused-vars */
import React from "react";
import { Project } from "../gql-codegen/graphql";

export interface IProjectContextType {
  projects: Map<string, Project>;
  addProjects: (p: Project[]) => void;
  addProject: (p: Project) => void;
  updateProject: (p: Project) => void;
  getProject: (id: string) => Project | undefined;
  getProjects: () => Project[];
}

const defaultValue: IProjectContextType = {
  projects: {} as Map<string, Project>,
  addProjects: (p: Project[]) => undefined,
  addProject: (p: Project) => undefined,
  updateProject: (p: Project) => undefined,
  getProject: (id: string) => undefined,
  getProjects: () => [],
};

export const ProjectContext = React.createContext<IProjectContextType>(
  defaultValue as IProjectContextType,
);

const ProjectProvider: React.FC<React.ReactNode> = ({ children }) => {
  const [projects, setProjects] = React.useState<Map<string, Project>>(
    new Map<string, Project>(),
  );

  const addProjects = (p: Project[]) => {
    try {
      // const c: Map<string, Project> = new Map<string, Project>();
      p.forEach((pr: Project) => projects.set(pr.id, pr));
      // setProjects(c);
    } catch (e) {
      console.error(e);
      setProjects(new Map<string, Project>());
    }
  };

  const addProject = (p: Project) => {
    projects.set(p.id, p);
  };

  const updateProject = (p: Project) => {
    projects.set(p.id, { ...projects.get(p.id), ...p });
  };

  const getProject = (s: string) => {
    return projects.get(s);
  };

  const getProjects = () => {
    try {
      return Array.from(projects.values());
    } catch (e) {
      console.error(e);
      return [];
    }
  };

  return (
    <ProjectContext.Provider
      value={{
        projects,
        addProject,
        addProjects,
        updateProject,
        getProject,
        getProjects,
      }}
    >
      {children}
    </ProjectContext.Provider>
  );
};

export default ProjectProvider;
