package playlists.providers.google;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import playlists.api.Artist;
import playlists.api.PlayListEntry;
import playlists.api.Song;
import playlists.api.repository.PlayListEntryRepository;
import playlists.api.repository.YouTubeVidRepository;

import java.util.List;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:mainContext.xml"})
@Transactional
public class YouTubeServiceTest {
    @Autowired
    YouTubeService youTubeService;

    @Autowired
    YouTubeVidRepository repository;

    @Autowired
    PlayListEntryRepository playListEntryRepository;

    @Test
    public void testGetVidUrl() throws Exception {
        String spotifySongId = "0ULPav7qqKTHn7vgi9v42k";
        Song song = new Song("Enjoy the Silence", 360, spotifySongId);
        Artist artist = new Artist("Depeche Mode", "someId");
        final YouTubeVid youTubeVid = youTubeService.getTopRatedVideoForSearch("Depeche Mode", "Enjoy the Silence", spotifySongId);
        PlayListEntry playListEntry = new PlayListEntry(song, artist);
        playListEntry.setVideo(youTubeVid);
        playListEntry = playListEntryRepository.save(playListEntry);

        assertEquals("aGSKrC7dGcY", youTubeVid.youTubeId);
        assertEquals(1, repository.findAll().size());
        assertEquals(1, playListEntryRepository.findAll().size());

        YouTubeVid saved = repository.findOne(youTubeVid.youTubeId);
        assertEquals(youTubeVid, saved);

        List<YouTubeVid> vidsForThisId = repository.findBySpotifySongId(spotifySongId);
        assertEquals(youTubeVid, vidsForThisId.iterator().next());
    }

    @Test
    public void testGetVidUrls() throws Exception {
        final Set<YouTubeVid> youTubeVids = youTubeService.getTopTenVideosForSearch("Depeche Mode", "Enjoy the Silence");
        assertEquals(10, youTubeVids.size());
        assertEquals(0, repository.findAll().size()); // Should not be saved using this method
    }

    @Test
    public void testGetAndSaveVid() throws Exception {
        String youTubeVidId = "HDI9inno86U";
        YouTubeVid youtubeVid = youTubeService.getYoutubeVid(youTubeVidId, true);
        YouTubeVid stored = repository.findOne(youTubeVidId);
        assertNotNull(stored);
        assertEquals(youtubeVid, stored);
        assertEquals("twenty one pilots: Fairly Local [OFFICIAL VIDEO]", youtubeVid.title);
    }
}
