/*
 * Kylin-video
 *
 * Copyright (C) 2021, Tianjin KYLIN Information Technology Co., Ltd.
 *
 * 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 3 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, see <https://www.gnu.org/licenses/>.
 *
 * Authors: Liu Cong <liucong1@kylinos.cn>
 *
 */

#include "subtracks.h"
#include <QSettings>

SubTracks::SubTracks()
{
    index = 0;
}

SubTracks::~SubTracks()
{

}

int SubTracks::find(SubData::Type t, int ID)
{
    for (unsigned int n=0; n < subs.count(); n++) {
        if ( ( subs[n].type() == t ) && ( subs[n].ID() == ID ) ) {
            return n;
        }
    }
    qDebug("SubTracks::find: item type: %d, ID: %d doesn't exist", t, ID);
    return -1;
}

void SubTracks::add(SubData::Type t, int ID)
{
    SubData d;
    d.setType(t);
    d.setID(ID);

    subs.append(d);
}

bool SubTracks::changeLang(SubData::Type t, int ID, QString lang)
{
    int f = find(t,ID);
    if (f == -1) return false;

    subs[f].setLang(lang);
    return true;
}

bool SubTracks::changeName(SubData::Type t, int ID, QString name)
{
    int f = find(t,ID);
    if (f == -1) return false;

    subs[f].setName(name);
    return true;
}

bool SubTracks::changeFilename(SubData::Type t, int ID, QString filename)
{
    int f = find(t,ID);
    if (f == -1) return false;

    subs[f].setFilename(filename);
    return true;
}

SubData SubTracks::itemAt(int n)
{
    if (n >= 0 && n < subs.count()) {
        return subs[n];
    } else {
        qWarning("SubTracks::itemAt: %d out of range!", n);
        qWarning("SubTracks::itemAt: returning an empty sub to avoid a crash");
        qWarning("SubTracks::itemAt: this shouldn't happen, report a bug if you see this");

        SubData empty_sub;
        return empty_sub;
    }
}

SubData SubTracks::findItem(SubData::Type t, int ID)
{
    SubData sub;
    int n = find(t,ID);
    if ( n != -1 )
        return subs[n];
    else
        return sub;
}

void SubTracks::save(QSettings *set, const QString &name)
{
    set->beginWriteArray(name);
    for (int n = 0; n < numItems(); n++) {
        set->setArrayIndex(n);
        SubData d = itemAt(n);
        set->setValue("id", d.ID());
        set->setValue("lang", d.lang());
        set->setValue("name", d.name());
        set->setValue("type", d.type());
        set->setValue("filename", d.filename());
    }
    set->endArray();
}
