/***************************************************************************
 *   Copyright (C) 2008-2025 by Ilya Kotov                                 *
 *   forkotov02@ya.ru                                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QFile>
#include <QDir>
#include <QDirIterator>
#include <QSettings>
#include <QTextStream>
#include <qmmp/decoder.h>
#include <qmmp/metadatamanager.h>
#include <qmmp/qmmptextcodec.h>
#ifdef WITH_ENCA
#include <enca.h>
#endif
#include "cuefile.h"

CueFile::CueFile(const QString &path) : CueParser()
{
    m_filePath = path.contains(u"://"_s) ? TrackInfo::pathFromUrl(path) : path;

    QFile file(m_filePath);
    if (!file.open(QIODevice::ReadOnly))
    {
        qCDebug(plugin, "error: %s", qPrintable(file.errorString()));
        return;
    }
    QByteArray data = file.readAll();
    file.close();

    QSettings settings;
    settings.beginGroup(u"CUE"_s);
    m_dirty = settings.value(u"dirty_cue"_s, false).toBool();
    QmmpTextCodec *codec = nullptr;
#ifdef WITH_ENCA
    EncaAnalyser analyser = nullptr;
    if(settings.value(u"use_enca"_s, false).toBool())
    {
        analyser = enca_analyser_alloc(settings.value(u"enca_lang"_s).toByteArray ().constData());

        if(analyser)
        {
            enca_set_threshold(analyser, 1.38);
            EncaEncoding encoding = enca_analyse(analyser, (uchar *)data.constData(), data.size());
            if(encoding.charset != ENCA_CS_UNKNOWN)
            {
                codec = new QmmpTextCodec(enca_charset_name(encoding.charset,ENCA_NAME_STYLE_ENCA));
                //qCDebug(plugin, "detected charset: %s",
                //       enca_charset_name(encoding.charset,ENCA_NAME_STYLE_ENCA));
            }
            enca_analyser_free(analyser);
        }
    }
#endif
    if(!codec)
        codec = new QmmpTextCodec(settings.value(u"encoding"_s, u"UTF-8"_s).toByteArray ());
    settings.endGroup();
    //qCDebug(plugin, "using %s encoding", codec->name().constData());
    loadData(data, codec);
    delete codec;
    setUrl(u"cue"_s, m_filePath);
    for(const QString &dataFileName : files())
    {
        QString dataFilePath = getDirtyPath(m_filePath, QFileInfo(m_filePath).dir().filePath(dataFileName));
        m_dataFiles.insert(dataFileName, dataFilePath);
        QList<TrackInfo *> pl = MetaDataManager::instance()->createPlayList(dataFilePath, TrackInfo::Properties);
        if(!pl.isEmpty())
        {
            setProperties(dataFileName, pl.constFirst()->properties());
            setDuration(dataFileName, pl.constFirst()->duration());
            qDeleteAll(pl);
            pl.clear();
        }
    }

    for(const QString &p : std::as_const(m_dataFiles))
    {
        if(!QFile::exists(p))
        {
            qCDebug(plugin, "unable to find file: %s", qPrintable(p));
            clear();
            return;
        }
    }
}

CueFile::~CueFile()
{}

QString CueFile::cueFilePath() const
{
    return m_filePath;
}

QString CueFile::dataFilePath(int track) const
{
    return m_dataFiles.value(file(track));
}

QStringList CueFile::dataFilePaths() const
{
    return m_dataFiles.values();
}

QStringList CueFile::splitLine(const QString &line)
{
    //qCDebug(plugin, "raw string = %s",qPrintable(line));
    QStringList list;
    QString buf = line.trimmed();
    if (buf.isEmpty())
        return list;
    while (!buf.isEmpty())
    {
        //qCDebug(plugin) << buf;
        if (buf.startsWith(QLatin1Char('"')))
        {
            int end = buf.indexOf(QLatin1Char('"'), 1);
            if(end == -1) //ignore invalid line
            {
                list.clear();
                qCWarning(plugin, "unable to parse line: %s",qPrintable(line));
                return list;
            }
            list << buf.mid (1, end - 1);
            buf.remove (0, end + 1);
        }
        else
        {
            int end = buf.indexOf(QChar::Space, 0);
            if (end < 0)
                end = buf.size();
            list << buf.mid(0, end);
            buf.remove(0, end);
        }
        buf = buf.trimmed();
    }
    return list;
}

QString CueFile::getDirtyPath(const QString &cue_path, const QString &path)
{    
    if((QFile::exists(path) && Decoder::findByFilePath(path)))
        return path;

    QStringList candidates;
    QDirIterator it(QFileInfo(path).dir().path(), QDir::Files);
    while (it.hasNext())
    {
        it.next();

        QString f = it.filePath();

        if(it.fileName().toLower() == QFileInfo(path).fileName().toLower() && Decoder::findByFilePath(f))
            return it.filePath();

        if(m_dirty && (f != cue_path) && Decoder::findByFilePath(f))
            candidates.push_back(f);
    }

    if (candidates.isEmpty())
        return path;

    if (candidates.count() == 1)
        return candidates.constFirst();

    int dot = cue_path.lastIndexOf(QLatin1Char('.'));
    if (dot != -1)
    {
        QRegularExpression r(QRegularExpression::escape(cue_path.left(dot)) + u"\\.[^\\.]+$"_s);

        int index = candidates.indexOf(r);
        int rindex = candidates.lastIndexOf(r);

        if ((index != -1) && (index == rindex))
            return candidates[index];
    }
    dot = path.lastIndexOf(QLatin1Char('.'));
    if (dot != -1)
    {
        QRegularExpression r(QRegularExpression::escape(path.left(dot)) + u"\\.[^\\.]+$"_s);

        int index = candidates.indexOf(r);
        int rindex = candidates.lastIndexOf(r);

        if ((index != -1) && (index == rindex))
            return candidates[index];
    }

    return path;
}
