const { getPlayUrlWithOptions } = require('../service/songs_info');
const { matchUrlFromStr } = require('../utils/regex');
const { searchSongs, getSongInfo, buildSongUrl } = require('../service/music_platform/tunehub');
const configManager = require('../service/config_manager');

function buildPageUrl(source, songId) {
    if (!source || !songId) {
        return '';
    }
    if (source === 'netease') {
        return `https://music.163.com/song?id=${songId}`;
    }
    if (source === 'qq') {
        return `https://y.qq.com/n/ryqq/songDetail/${songId}`;
    }
    return '';
}

function mapTunehubResult(item) {
    const playUrl = item.url || buildSongUrl(item.platform, item.id);
    const pageUrl = buildPageUrl(item.platform, item.id);
    return {
        songId: item.id || '',
        songName: item.name || '',
        artist: item.artist || '',
        album: item.album || '',
        duration: 0,
        url: pageUrl || playUrl || '',
        playUrl: playUrl || '',
        pageUrl: pageUrl || '',
        coverUrl: item.pic || '',
        resourceForbidden: false,
        source: item.platform || '',
        fromMusicPlatform: true,
        score: 0,
    };
}

function parseNeteaseSongId(url) {
    const match = url.match(/song\\?id=(\\d+)/);
    if (match && match[1]) {
        return match[1];
    }
    const altMatch = url.match(/\\bid=(\\d+)/);
    if (altMatch && altMatch[1]) {
        return altMatch[1];
    }
    return '';
}

async function search(req, res) {
    const query = req.query;

    const keywordOrUrl = query.keyword;

    if (!keywordOrUrl) {
        res.send({
            status: 1,
            message: "keyword is required",
        });
        return;
    }
    let keyword = keywordOrUrl;
    const url = matchUrlFromStr(keywordOrUrl);
    if (url) {
        const neteaseId = parseNeteaseSongId(url);
        if (neteaseId) {
            const info = await getSongInfo('netease', neteaseId);
            if (info && info.name && info.artist) {
                keyword = `${info.name} ${info.artist}`;
            }
        }
    }

    const limit = query.limit ? parseInt(query.limit, 10) : 20;
    const requestSource = query.source || '';
    const searchData = await searchSongs(keyword, {
        source: requestSource,
        limit: Number.isNaN(limit) ? 20 : limit,
        aggregate: !requestSource,
    });
    if (searchData === false || !searchData.results) {
        res.send({
            status: 0,
            data: {
                songs: [],
            }
        });
        return;
    }

    const globalConfig = await configManager.getGlobalConfig();
    const enabledSources = globalConfig && Array.isArray(globalConfig.sources) ? globalConfig.sources : [];
    const songs = searchData.results
        .filter(item => {
            if (!item.platform) {
                return false;
            }
            if (enabledSources.length === 0) {
                return true;
            }
            return enabledSources.includes(item.platform);
        })
        .map(mapTunehubResult)
        .filter(song => song.songName.length > 0);

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

async function getPlayUrl(req, res) {
    const source = req.params.source;
    const songId = req.params.id;

    if (!source || !songId) {
        res.send({
            status: 1,
            message: "source and songId is required",
        });
        return;
    }
    const playUrl = await getPlayUrlWithOptions(req.account.uid, source, songId);

    res.send({
        status: 0,
        data: {
            playUrl,
        }
    });
}

module.exports = {
    search: search,
    getPlayUrl: getPlayUrl
}
