import React from 'react';
import Integration, { IntegrationFeature, IntegrationAlbum, IntegrationArtist, IntegrationTrack } from '../Integration';
import StoreLinkIcon from '../../../components/common/StoreLinkIcon';
import { IntegrationWith } from '../../../api/api';

enum SearchType {
    Track = 'track',
    Artist = 'artist',
    Album = 'album',
};

export default class SpotifyClientCreds extends Integration {
    integrationId: number;

    constructor(integrationId: number) {
        super(integrationId);
        this.integrationId = integrationId;
    }

    getFeatures(): IntegrationFeature[] {
        return [
            IntegrationFeature.Test,
            IntegrationFeature.SearchTrack,
            IntegrationFeature.SearchAlbum,
            IntegrationFeature.SearchArtist,
        ]
    }

    getIcon(props: any) {
        return <StoreLinkIcon whichStore={IntegrationWith.Spotify} {...props} />
    }

    providesStoreLink() {
        return IntegrationWith.Spotify;
    }

    async test(testParams: {}) {
        const response = await fetch(
            (process.env.REACT_APP_BACKEND || "") +
            `/integrations/${this.integrationId}/v1/search?q=queens&type=artist`);

        if (!response.ok) {
            throw new Error("Spotify Client Credentials test failed: " + JSON.stringify(response));
        }

        console.log("Spotify test response:", await response.json())
    }

    async searchTrack(query: string, limit: number): Promise<IntegrationTrack[]> { 
        return this.search(query, SearchType.Track, limit);
    }
    async searchAlbum(query: string, limit: number): Promise<IntegrationAlbum[]> { 
        return this.search(query, SearchType.Album, limit);
    }
    async searchArtist(query: string, limit: number): Promise<IntegrationArtist[]> { 
        return this.search(query, SearchType.Artist, limit);
    }

    async search(query: string, type: SearchType, limit: number):
        Promise<IntegrationTrack[] | IntegrationAlbum[] | IntegrationArtist[]> {
            const response = await fetch(
                (process.env.REACT_APP_BACKEND || "") +
                `/integrations/${this.integrationId}/v1/search?q=${encodeURIComponent(query)}&type=${type}&limit=${limit}`);
    
            if (!response.ok) {
                throw new Error("Spotify Client Credentials search failed: " + JSON.stringify(response));
            }

            let json = await response.json();

            console.log("Response:", json);

            switch(type) {
                case SearchType.Track: {
                    return json.tracks.items.map((r: any): IntegrationTrack => {
                        return {
                            title: r.name,
                            url: r.external_urls.spotify,
                            artist: {
                                name: r.artists && r.artists[0].name,
                                url: r.artists && r.artists[0].external_urls.spotify,
                            },
                            album: {
                                name: r.album && r.album.name,
                                url: r.album && r.album.external_urls.spotify,
                            }
                        }
                    })
                }
                case SearchType.Artist: {
                    return json.artists.items.map((r: any): IntegrationArtist => {
                        return {
                            name: r.name,
                            url: r.external_urls.spotify,
                        }
                    })
                }
                case SearchType.Album: {
                    return json.albums.items.map((r: any): IntegrationAlbum => {
                        return {
                            name: r.name,
                            url: r.external_urls.spotify,
                            artist: {
                                name: r.artists[0].name,
                                url: r.artists[0].external_urls.spotify,
                            },
                        }
                    })
                }
            }
        }
}