#include "autosyncpackinfo.h"
#include "globalinfo.h"
#include <QTimer>

AutoSyncPackInfo::AutoSyncPackInfo(QObject *parent) : QObject(parent),_server(nullptr)
{
    _manger = nullptr;
    inQueue = false;
}


void AutoSyncPackInfo::start()
{
    if(th == nullptr){
        th = new QThread(this);
        this->moveToThread(th);
        connect(th,&QThread::started,this,&AutoSyncPackInfo::doSend);
        th->start();
    } else {
        QTimer::singleShot(20,this,&AutoSyncPackInfo::doSend);
    }
}

void AutoSyncPackInfo::sync(const QDate & dt)
{
    if(GlobalInfo::this_()->isNoLine()) return;
    mutex.lock();
    _dateQueue.append(dt);
    mutex.unlock();
    QTimer::singleShot(20,this,&AutoSyncPackInfo::doQueue);
}

void AutoSyncPackInfo::doQueue()
{
    if(inQueue) return;
    if(_manger == nullptr)
        _manger = GlobalInfo::this_()->packInfoManger();
    if(_server == nullptr) {
        _server = new PackInfoSeed2Server(_manger,this,false);
        connect(_server,&PackInfoSeed2Server::syncEnd,this,&AutoSyncPackInfo::syncedOne);
    }
    if(_dateQueue.isEmpty()) return;
    QDate n = _dateQueue.first();
    auto list =  _manger->getPackInfo(n,true);
    QList<QSharedPointer<PackInfo>> infos;
    for(int i = 0; i < list.size(); ++i){
        infos.append(list.at(i).packInfo);
    }
    _server->sendList(infos);
}

void AutoSyncPackInfo::loadOut()
{
    mutex.lock();
    _dateQueue.clear();
    mutex.unlock();
}

void AutoSyncPackInfo::doSend()
{
    if(GlobalInfo::this_()->isNoLine()) return;
    if(_manger == nullptr)
        _manger = GlobalInfo::this_()->packInfoManger();
    QDate dt = QDate::currentDate();
    int td = -15;
    while(true){
        auto tdd = dt.addDays(td);
        auto list = _manger->getPackInfo(tdd,true);
        if(!list.isEmpty()) {
            td -= 7;
        } else {
            break;
        }
    }
    mutex.lock();
    for(int i = td; i < 0; ++i){
        _dateQueue.append(dt.addDays(td));
    }
//    _dateQueue.append(dt);
    mutex.unlock();
}

void AutoSyncPackInfo::syncedOne()
{
    if(_dateQueue.isEmpty()) return;
    mutex.lock();
    _dateQueue.dequeue();
    mutex.unlock();
    QTimer::singleShot(20,this,&AutoSyncPackInfo::doQueue);
}
