#include "sequenceentry.h"
using Xybrid::Data::SequenceEntry;

#include "data/pattern.h"
#include "data/project.h"
#include "util/strings.h"

#include <QCborValue>
#include <QCborMap>

SequenceEntry::SequenceEntry(Project* project, const QCborValue& v) {
    if (v.isInteger()) {
        qint64 i = v.toInteger();
        if (i < 0 || i >= static_cast<qint64>(project->patterns.size())) { return; } // out of range; treat as separator
        type = Pattern;
        p = project->patterns[static_cast<size_t>(i)];
        return;
    } else if (v.isString()) {
        QString s = v.toString();
        if (s == qs("l")) { type = LoopStart; }
        else if (s == qs("lt")) { type = LoopTrigger; }
    }
}

Xybrid::Data::SequenceEntry::operator QCborValue() const {
    if (type == Separator) return -1;
    if (type == Pattern) if (auto pt = pattern(); pt) return static_cast<qint64>(pt->index);
    if (type == LoopStart) return qs("l");
    if (type == LoopTrigger) return qs("lt");
    return { };
}

QString SequenceEntry::symbol() const {
    if (type == Pattern) {
        auto p = pattern();
        if (!p) return qs("(!)");
        return QString::number(p->index);
    }
    if (type == Separator) return qs("-");
    if (type == LoopStart) return qs("|");
    if (type == LoopTrigger) return qs("<<");
    return { };
}

QString SequenceEntry::toolTip() const {
    if (type == Pattern) {
        auto p = pattern();
        if (!p) return qs("(missing pattern)");
        if (p->name.isEmpty()) return { }; // no tooltip
        return Util::numAndName(p->index, p->name);
    }
    if (type == Separator) return qs("(separator)");
    if (type == LoopStart) return qs("(loop point)");
    if (type == LoopTrigger) return qs("(trigger loop)");
    return { };
}
