const logger = require('consola');
const { getUserAllPlaylist } = require('../service/music_platform/wycloud');
const { getPlaylistDetail } = require('../service/music_platform/tunehub');
const Source = require('../consts/source').consts;

function splitArtists(artist) {
    if (!artist) {
        return [];
    }
    return artist
        .split(/[、/]/)
        .map(item => item.trim())
        .filter(Boolean);
}

function normalizeTunehubPlaylist(playlistId, detail) {
    const info = detail && detail.info ? detail.info : {};
    const list = detail && Array.isArray(detail.list) ? detail.list : [];

    const songs = list.map(item => {
        const artists = splitArtists(item.artist);
        const primaryArtist = artists[0] || item.artist || '';
        const cover = item.pic || info.pic || '';
        const isBlocked = !item.types || item.types.length === 0;
        return {
            songId: item.id,
            songName: item.name || '',
            artists,
            artist: primaryArtist,
            duration: 0,
            album: item.album || '',
            cover,
            pageUrl: `https://music.163.com/song?id=${item.id}`,
            playUrl: item.url || '',
            isBlocked,
            isCloud: false,
        };
    });

    return {
        id: playlistId,
        name: info.name || '',
        cover: info.pic || '',
        songs,
    };
}

async function listAllPlaylists(req, res) {
    const uid = req.account.uid;
    const playlists = await getUserAllPlaylist(uid);
    if (playlists === false) {
        logger.error(`get user all playlist failed, uid: ${uid}`);
    }

    res.send({
        status: playlists ? 0 : 1,
        data: {
            playlists,
        }
    });
}

async function listSongsFromPlaylist(req, res) {
    const uid = req.account.uid;
    const source = req.params.source;
    const playlistId = req.params.id;

    if (source !== Source.Netease.code || !playlistId) {
        res.send({
            status: 1,
            message: "source or id is invalid",
        });
        return;
    }
    const detail = await getPlaylistDetail(source, playlistId);
    if (detail === false) {
        logger.error(`get playlist detail failed, uid: ${uid}`);
    }
    const playlists = detail ? normalizeTunehubPlaylist(playlistId, detail) : false;

    res.send({
        status: playlists ? 0 : 1,
        data: {
            playlists: playlists ? playlists : [],
        }
    });
}

module.exports = {
    listAllPlaylists: listAllPlaylists,
    listSongsFromPlaylist: listSongsFromPlaylist,
}
