#include "filepicker.h"
#include "helper.h"
#include "framework/common/errorinfo.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <dirent.h>

Filepicker::Filepicker()
{
}

Filepicker::~Filepicker()
{
    if(filepickerQml != nullptr){
        filepickerQml->deleteLater();
    }
}

void Filepicker::invokeInitialize()
{
}

void Filepicker::invoke(const QString &callbackID, const QString &actionName, const QVariantMap &params)
{
    qDebug() << Q_FUNC_INFO << "  callbackID:" << callbackID << "actionName:" << actionName << "params:" << params;

    if (actionName == "open") {
        open(callbackID, params);
    }
}

void Filepicker::open(const QString &callbackID, const QVariantMap &params)
{
    qDebug() << Q_FUNC_INFO  << params;
    globalCallbackID = callbackID.toLong();

    QString title = params.value("title").toString();
    bool showBack = params.value("showBack", false).toBool();
    QString category = params.value("category", "all").toString();
    int count = params.value("count", 1).toInt();
    qDebug() << "params"<<"title: "<<title<<"category: "<<category<<"path: ";

    filepickerQml = qmlManager.open("qrc:/qml/SFilesPicker.qml");

    qmlManager.setProperty(filepickerQml, "titleText", title);
    qmlManager.setProperty(filepickerQml, "leftItemEnabled", showBack);
    qmlManager.setProperty(filepickerQml, "categoryType", category);
    qmlManager.setProperty(filepickerQml, "count", count);

    qmlManager.connectSignal(filepickerQml, SIGNAL(ok(QString)), this, SLOT(chooseOk(QString)));
    qmlManager.connectSignal(filepickerQml, SIGNAL(cancel()), this, SLOT(chooseCancel()));
}

void Filepicker::chooseOk(const QString &filesPath)
{
    // js传递json字符串过来
    qDebug() << Q_FUNC_INFO << "filesPath " << filesPath;

    if (filepickerQml != nullptr) {
        filepickerQml->deleteLater();
        filepickerQml = nullptr;
    }

    QJsonDocument jsonDocument = QJsonDocument::fromJson(filesPath.toUtf8());
    if (jsonDocument.isNull()) {
        qDebug()<< "===> please check the string "<< filesPath.toLocal8Bit().data();
        signalManager()->failed(globalCallbackID, ErrorInfo::PluginError, "返回数据格式错误");
        return;
    }

    // json字符串转换为QJsonArray
    QJsonObject result = jsonDocument.object();

    qDebug() << Q_FUNC_INFO << "result***************" << result;

    signalManager()->success(globalCallbackID, QVariant(result));

    globalCallbackID = 0;
}

void Filepicker::chooseCancel()
{
    qDebug() << Q_FUNC_INFO;

    if (filepickerQml != nullptr) {
        filepickerQml->deleteLater();
        filepickerQml = nullptr;
    }
    signalManager()->success(globalCallbackID, "");
    globalCallbackID = 0;
}
