import { useState, useEffect } from 'react';
import { getJamTrack } from '../helpers/rest';
import { useAppData } from '../context/AppDataContext';

const useJamTrackAudio = jamTrack => {
  const [audioUrls, setAudioUrls] = useState([]);
  const [jamTrackRecord, setJamTrackRecord] = useState(jamTrack);
  //const fpPromise = FingerprintJS.load();
  const { appData } = useAppData();
  

  const loadJamTrack = async () => {
    //console.log('_JAMTRACK_ loading jam track');
    try {
      const resp = await getJamTrack({ id: jamTrack.id });
      const data = await resp.json();
      setJamTrackRecord(data);
    } catch (error) {
      console.log('Error when fetching jam track', error);
    }
  };

  const updateMedia = async () => {
    //console.log('_JAMTRACK_ updating media', jamTrackRecord);
    const activeMixdown = jamTrackRecord.mixdowns.find(mixdown => mixdown.id === jamTrackRecord.last_mixdown_id);
    const activeStem = jamTrackRecord.tracks.find(stem => stem.id === jamTrackRecord.last_stem_id);
   
  
    if (activeStem) {
      //console.log('_JAMTRACK_ this is a stem', activeStem);
    } else if (activeMixdown) {
      //console.log('_JAMTRACK_ this is a mixdown', activeMixdown);
      //const fp = await fpPromise;
      //const result = await fp.get();
      const audioUrl =
        process.env.REACT_APP_API_BASE_URL +
        `/mixdowns/${activeMixdown.id}/download.mp3?file_type=mp3&sample_rate=48&mark=${appData?.visitorId}`;
        console.log('mixdown audioUrl', audioUrl);
      setAudioUrls([audioUrl]);
    } else if (jamTrack) {
      const masterTrack = jamTrack.tracks.find(track => track.track_type === 'Master');
      //console.log('_JAMTRACK_ this is the master track', masterTrack);
      if (masterTrack) {
        setAudioUrls([masterTrack.preview_mp3_url]);
      }
    }
  };

  // useEffect(() => {
  //   if (!jamTrack) {
  //     return;
  //   }
  //   loadJamTrack();
  // }, [jamTrack]);

  useEffect(() => {
    if (jamTrackRecord) {
      updateMedia();
    }
  }, [jamTrackRecord]);

  return { audioUrls, loadJamTrack };
};

export default useJamTrackAudio;
