import { defineStore } from "pinia";
import type {
  VehicleViewModel,
  CreateVehicleViewModel,
  UpdateVehicleViewModel,
} from "@/viewmodels/admin/unit/vehicle/vehicle.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";
import { vehicleDemoData } from "@/demodata/vehicle";

export const useVehicleStore = defineStore("vehicle", {
  state: () => {
    return {
      vehicles: [] as Array<VehicleViewModel & { tab_pos: number }>,
      totalCount: 0 as number,
      loading: "loading" as "loading" | "fetched" | "failed",
      activeVehicle: null as string | null,
      activeVehicleObj: null as VehicleViewModel | null,
      loadingActive: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchVehicles(offset = 0, count = 25, search = "", clear = false) {
      this.vehicles = vehicleDemoData.map((e, i) => ({ ...e, tab_pos: i }));
      this.totalCount = this.vehicles.length;
      this.loading = "fetched";
      return;
      if (clear) this.vehicles = [];
      this.loading = "loading";
      http
        .get(`/admin/vehicle?offset=${offset}&count=${count}${search != "" ? "&search=" + search : ""}`)
        .then((result) => {
          this.totalCount = result.data.total;
          result.data.vehicles
            .filter((elem: VehicleViewModel) => this.vehicles.findIndex((m) => m.id == elem.id) == -1)
            .map((elem: VehicleViewModel, index: number): VehicleViewModel & { tab_pos: number } => {
              return {
                ...elem,
                tab_pos: index + offset,
              };
            })
            .forEach((elem: VehicleViewModel & { tab_pos: number }) => {
              this.vehicles.push(elem);
            });
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    async getAllVehicles(): Promise<AxiosResponse<any, any>> {
      return await http.get(`/admin/vehicle?noLimit=true`).then((res) => {
        return { ...res, data: res.data.vehicles };
      });
    },
    async getVehiclesByIds(ids: Array<string>): Promise<AxiosResponse<any, any>> {
      return await http
        .post(`/admin/vehicle/ids`, {
          ids,
        })
        .then((res) => {
          return { ...res, data: res.data.vehicles };
        });
    },
    async searchVehicles(search: string): Promise<AxiosResponse<any, any>> {
      return await http.get(`/admin/vehicle?search=${search}&noLimit=true`).then((res) => {
        return { ...res, data: res.data.vehicles };
      });
    },
    fetchVehicleByActiveId() {
      this.activeVehicleObj = vehicleDemoData.find((e) => e.id == this.activeVehicle) as VehicleViewModel;
      this.loadingActive = "fetched";
      return;
      this.loadingActive = "loading";
      http
        .get(`/admin/vehicle/${this.activeVehicle}`)
        .then((res) => {
          this.activeVehicleObj = res.data;
          this.loadingActive = "fetched";
        })
        .catch((err) => {
          this.loadingActive = "failed";
        });
    },
    fetchVehicleById(id: string) {
      return http.get(`/admin/vehicle/${id}`);
    },
    async createVehicle(vehicle: CreateVehicleViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.post(`/admin/vehicle`, {
        // TODO: data
      });
      this.fetchVehicles();
      return result;
    },
    async updateActiveVehicle(vehicle: UpdateVehicleViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/vehicle/${vehicle.id}`, {
        // TODO: data
      });
      this.fetchVehicles();
      return result;
    },
    async deleteVehicle(vehicle: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/vehicle/${vehicle}`);
      this.fetchVehicles();
      return result;
    },
  },
});