#include "packinfomanger.h"
#include <pqQtlib/core/pqapppath.h>
#include <pqQtlib/utils/pqfileutils.h>
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonArray>
#include "QDebug"

using namespace PQ;

PackInfoManger::PackInfoManger(QObject *parent) : QObject(parent)
{
    _dataDir = AppPath::this_()->dataDir();
    if(!_dataDir.exists("packinfo")){
        _dataDir.mkdir("packinfo");
    }
    _dataDir.cd("packinfo");
}


QString PackInfoManger::savePackInfo(const QSharedPointer<PackInfo> & info)
{
    if(info.isNull()) return "";
    auto tm = QDateTime::fromSecsSinceEpoch(info->time());
    auto dir = getDir(tm.date(),true);
    QString name = info->codeSingle();
    name += "_sync.json";
    QString ret = dir.absoluteFilePath(name);
    if(writeAbsoluteFile(ret,QJsonDocument(info->toObject()).toJson()))
        return ret;
    return "";
}

QString PackInfoManger::setPackInfoSync(const QString & code, qint64 time, bool autoSync)
{
    QDateTime tm;
    if(time < 0){
        tm = QDateTime::currentDateTime();
    } else {
        tm = QDateTime::fromSecsSinceEpoch(time);
    }
    auto dir = getDir(tm.date());
    QString name = dir.absoluteFilePath(code +  "_sync.json");
    QString newName = dir.absoluteFilePath(code + ".json");
    if(QFile::rename(name,newName) && autoSync){
        writeAbsoluteFile(_dataDir.absoluteFilePath("auto_sync.time"),tm.toString("yyyy-MM-dd").toUtf8());
        return newName;
    }
    return "";
}

QDate PackInfoManger::lastSyncDate()
{
    QByteArray dt = readAbsoluteFile(_dataDir.absoluteFilePath("sync.time"));
    if(dt.isEmpty()) {
        QDate ret = QDate::currentDate().addDays(-30);
        writeAbsoluteFile(_dataDir.absoluteFilePath("auto_sync.time"),ret.toString("yyyy-MM-dd").toUtf8());
    }
    return QDate::fromString(QString::fromUtf8(dt),"yyyy-MM-dd");
}


QDir PackInfoManger::getDir(const QDate & tm, bool create)
{
    QString dirName = tm.toString("yyyy-MM-dd");
    if(create && !_dataDir.exists(dirName)){
        _dataDir.mkdir(dirName);
    }
    qDebug()<<_dataDir.absoluteFilePath(dirName);
    return QDir(_dataDir.absoluteFilePath(dirName));
}


QList<PackSaveInfo> PackInfoManger::getPackInfo(const QDate & tm,bool noSync)
{
    auto dir = getDir(tm);
    auto list  = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files);
    QList<PackSaveInfo> ret;
    for(int i = 0; i < list.size(); ++i){
        auto & finfo = list.at(i);
        if(noSync && finfo.fileName().indexOf("_sync") > 0) continue;
        auto obj = QJsonDocument::fromJson(readAbsoluteFile(finfo.absoluteFilePath())).object();
        auto info = PackInfo::fromObject(obj);
        if(!info.isNull()){
            PackSaveInfo pinfo;
            pinfo.absPath = finfo.absoluteFilePath();
            pinfo.packInfo = info;
            ret.append(pinfo);
        }
    }
    return ret;
}

QList<QSharedPointer<BoxModel>> PackInfoManger::getBoxModel()
{
    auto dir =PQ::AppPath::this_()->dataDir();
    if(!dir.exists("BoxModel")){
        dir.mkdir("BoxModel");
    }
    dir.cd("BoxModel");

    auto list  = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files);
    QList<QSharedPointer<BoxModel>> ret;
    for(int i = 0; i < list.size(); ++i){
        auto & finfo = list.at(i);
        auto obj = QJsonDocument::fromJson(readAbsoluteFile(finfo.absoluteFilePath())).object();
        auto info = BoxModel::fromObject(obj);
        if(!info.isNull()){
            ret.append(info);
        }
    }
    return ret;
}

QList<QSharedPointer<PackModel>> PackInfoManger::getPackModel()
{
    auto dir =PQ::AppPath::this_()->dataDir();
    if(!dir.exists("PackModel")){
        dir.mkdir("PackModel");
    }
    dir.cd("PackModel");

//    QList<QSharedPointer<PackModel>> packmodel;

    auto list  = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files);
    QList<QSharedPointer<PackModel>> ret;
    for(int i = 0; i < list.size(); ++i){
        auto & finfo = list.at(i);
        auto obj = QJsonDocument::fromJson(readAbsoluteFile(finfo.absoluteFilePath())).object();
        auto info = PackModel::fromObject(obj);
        if(!info.isNull()){
            ret.append(info);
        }
    }
    return ret;
}

QList<PackSaveInfo> PackInfoManger::getPackInfoSync(const QDate &tm)
{
    auto dir = getDir(tm);
    auto list  = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files);
    QList<PackSaveInfo> ret;
    for(int i = 0; i < list.size(); ++i){
        auto & finfo = list.at(i);
        if(finfo.fileName().indexOf("_sync") < 0) continue;
        auto obj = QJsonDocument::fromJson(readAbsoluteFile(finfo.absoluteFilePath())).object();
        auto info = PackInfo::fromObject(obj);
        if(!info.isNull()){
            PackSaveInfo pinfo;
            pinfo.absPath = finfo.absoluteFilePath();
            pinfo.packInfo = info;
            ret.append(pinfo);
        }
    }
    return ret;
}


QList<QSharedPointer<ProjectInfo>>  PackInfoManger::getLocalProjectInfo()
{
    QList<QSharedPointer<ProjectInfo>> list;
    auto dt = readAbsoluteFile(_dataDir.absoluteFilePath("project.json"));
    if(!dt.isEmpty()) {
        QJsonArray ary = QJsonDocument::fromJson(dt).array();
        for(int i = 0; i < ary.size(); ++i){
            auto obj = ary.at(i).toObject();
            auto info = ProjectInfo::fromObject(obj);
            if(!info.isNull()) {
                info->isLocal = true;
                list.append(info);
            }
        }
    }
    return list;
}


bool PackInfoManger::syncLocalProjectInfo(QList<QSharedPointer<ProjectInfo> > &projects)
{
    QJsonArray ary;
    for(int i = 0; i < projects.size(); ++i)
    {
        ary.append(projects.at(i)->toObject());
    }
    QByteArray dt = QJsonDocument(ary).toJson();
    return writeAbsoluteFile(_dataDir.absoluteFilePath("project.json"),dt);
}
