import AsyncStorage from "@react-native-async-storage/async-storage";
import {Artist} from "../Model/Artist";

export const storeLikeArtists = async (artistsList) => {
    try {
        const jsonArtistsList = JSON.stringify(artistsList);
        await AsyncStorage.setItem('likeArtists', jsonArtistsList);
    } catch (e) {
        console.log("An error occurred while storing artists list", e);
    }
};

export const getLikeArtist = async () => {
    try {
        const jsonArtistsList = await AsyncStorage.getItem('likeArtists');
        const artistsList = jsonArtistsList !== null ? JSON.parse(jsonArtistsList) : [];
        return artistsList.map(artist => new Artist(artist._id,artist._name,artist._image));
    } catch (e) {
        console.log("An error occurred while retrieving artists list", e);
        return [];
    }
}
export const getLikeArtistJson = async () => {
    try {
        const jsonArtistsList = await AsyncStorage.getItem('likeArtists');
        return jsonArtistsList !== null ? JSON.parse(jsonArtistsList) : [];
    } catch (e) {
        console.log("An error occurred while retrieving artists list", e);
        return [];
    }
}

export const addLikeArtist = async (artist) => {
    try {
        const artistsList = await getLikeArtistJson();
        artistsList.push(artist);
        await storeLikeArtists(artistsList);
    } catch (e) {
        console.log("An error occurred while adding artist to the list", e);
    }
};


export const removeArtist = async (artistId) => {
    try {
        let artistsList = await getLikeArtistJson();
        artistsList = artistsList.filter(artist => artist._id !== artistId);
        console.log(artistsList);
        await storeLikeArtists(artistsList);
    } catch (e) {
        console.log("An error occurred while removing artist from the list", e);
    }
}