import { defineStore } from "pinia";
import PatientService from "@/services/patient.service";

export const usePatientsStore = defineStore({
  id: "patients",
  state: () => ({
    patients: [],
    loading: false,
    selectedPatient: {}
  }),
  getters: {
    getPatients: (state) => state.patients,
    getLoading: (state) => state.loading,
    getCurrentPatient: (state) => state.selectedPatient,
  },
  actions: {
    async load() {
      const userId = JSON.parse(sessionStorage.getItem('user')).id;
      await PatientService.load(userId).then(
        (response) => {
          console.log(response);
          this.patients = response;
          this.loading = false;
        },
        (error) => {
          console.log(error);
        }
      );
    },
    save(data) {
      // patient['user_id'] = JSON.parse(JSON.stringify(sessionStorage.getItem('user')));
      data['user_id'] = JSON.parse(sessionStorage.getItem('user')).id;
      if(data.sex === "") data.sex = "0";
      PatientService.save(data).then(
        (response) => {
          this.patients.push(response);
        },
        (error) => {
          console.log(error);
        }
		  );
    },
    update(data) {
      const findindex = this.patients.findIndex((e) => e.id === data.id);
      PatientService.update(data).then(
        (response) => {
          this.patients.splice(findindex, 1, response)
        },
        (error) => {
          console.log(error);
        }
		  );
    },
    delete(data) {
      PatientService.delete(data.id).then(
        (response) => {
          this.patients = this.patients.filter((item) => item.id !== data.id);
        },
        (error) => {
          console.log(error);
        }
      );
    },
  },
});
