#include "entry.h"

#include "chinese2pinyin.h"

using namespace Dtk::Util;

inline bool isAlphabeta(const QChar &c)
{
    QRegExp re("[A-Za-z]*");
    return re.exactMatch(c);
}

inline bool isNumber(const QChar &c)
{
    QRegExp re("[0-9]*");
    return re.exactMatch(c);
}

inline bool isChinese(const QChar &c)
{
    return c.unicode() < 0x9FBF && c.unicode() > 0x4E00;
}

inline QString toChinesePinyin(const QString &c)
{
    QString pinyin = Pinyin::Chinese2Pinyin(c);
    if (pinyin.length() >= 2
            && isNumber(pinyin.at(pinyin.length() - 1))) {
        return pinyin.left(pinyin.length() - 1);
    }
    return pinyin;
}

QStringList simpleChineseSplit(QString &pinyin)
{
    QStringList wordList;
    bool isLastAlphabeta = false;
    for (auto &c : pinyin) {
        bool isCurAlphabeta = isAlphabeta(c);
        if (isCurAlphabeta) {
            if (!isLastAlphabeta) {
                wordList << c;
            } else {
                wordList.last().append(c);
            }
            continue;
        }
        isLastAlphabeta = isCurAlphabeta;
        if (isNumber(c)) {
            wordList << c;
            continue;
        }
        if (isChinese(c)) {
            wordList << toChinesePinyin(c);
            continue;
        }
    }
    return wordList;
}

Entry::Entry(const QString &value, void *data)
{
    rawValue = value;
    rawData = data;

    for (auto &str : simpleChineseSplit(rawValue)) {
        pingyin += str;
        pingyinShort += str.at(0);
    }
}

QStringList Entry::keys() const
{
    return QStringList() << rawValue << pingyin << pingyinShort;
}

QString Entry::value() const
{
    return rawValue;
}

void *Entry::data() const
{
    return rawData;
}
