import { conf } from "@/api";
import { Star, StarsApi } from "@/swagger";
import { defineStore } from "pinia";

type ChartInfoState = {
  loading: boolean;
  stars: Star[];
  visiting: undefined | Star;
};

export const useChartStore = defineStore({
  id: "chart",
  state: () =>
    ({
      loading: true,
      stars: [],
      visiting: undefined,
    } as ChartInfoState),
  actions: {
    async fetchChart() {
      this.loading = true;
      this.stars = await new StarsApi(conf())
        .chart()
        .catch((e) => {
          console.error(e);
          return this.stars;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    async discover(color: string) {
      this.loading = true;
      await new StarsApi(conf())
        .discover({
          discoveryLog: { color: color },
        })
        .then((star) => {
          this.stars.push(star);
          this.visiting = star;
        })
        .catch((e) => {
          console.error(e);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    async visit(id: number) {
      const matching_stars = this.stars.filter((item) => {
        return item.core.id === id;
      });
      if (matching_stars.length >= 1) {
        this.visiting = matching_stars.pop();
        return;
      }
      this.loading = true;
      await new StarsApi(conf())
        .visit({ planetId: id })
        .then((star) => {
          this.stars.push(star);
          this.visiting = star;
        })
        .catch((e) => {
          console.error(e);
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
});
