import { makeAutoObservable } from "mobx"
import genreVectors from './genres.json'

export interface VectorResult {
  id: string
  vector: number[]
  type?: string
}

class EnergyState {
  choices: VectorResult[][] = []

  audioElement: HTMLAudioElement | null = null

  selectedChoices = new Set<string>();

  constructor() {
    makeAutoObservable(this)

    this.choices = [[...Object.entries(genreVectors).map(([key, value]) => {
      return (
        {
          vector: value,
          type: 'preset',
          id: key,
        }
      )
    }), {
      vector: [],
      type: 'random',
      id: 'random',
    }]]
  }

  setAudioElement(audioElement: HTMLAudioElement) {
    this.audioElement = audioElement
  }

  playId = (id: string) => {
    if (!this.audioElement) return;

    this.audioElement.src = `https://cdn1.suno.ai/${id}.mp3`
    this.audioElement.play()
    console.log('playing...')
  }

  pause = () => {
    if (!this.audioElement) return;

    this.audioElement.pause()
  }

  loadInitialData = async () => {
    this.selectedChoices.add('random')
    const response = await fetch("/api/energy");
    const data = (await response.json()).vectors as VectorResult[];
    console.log(data);
    const shuffled = data.sort(() => 0.5 - Math.random());
    this.choices.push(shuffled.slice(0, 10));
  }

  getSimilarIdToPreset = async (choice: VectorResult): Promise<string> => {
    const response = await fetch("/api/energy/similar", {
      method: 'POST',
      body: JSON.stringify(choice)
    });
    const data = (await response.json()) as VectorResult[];
    return data[Math.floor(Math.random() * data.length)].id
  }

  getSimilar = async (choice: VectorResult, rowIndex: number) => {
    this.choices[rowIndex].map((c) => {
      if (this.selectedChoices.has(c.id)) {
        this.selectedChoices.delete(c.id)
      }
    })
    this.selectedChoices.add(choice.id)
    this.choices = this.choices.slice(0, rowIndex + 1)

    const response = await fetch("/api/energy/similar", {
      method: 'POST',
      body: JSON.stringify(choice)
    });
    const data = (await response.json()) as VectorResult[];
    console.log(data);
    const randomSubset = data.slice(4, 16).sort(() => 0.5 - Math.random()).slice(0, 6);
    this.choices.push(randomSubset)
    // console.log(this.ids);
  }


}

export const energyState = new EnergyState()