#include "wprogramitem.h"
#include "loapptools.h"
#include "weditprogram.h"
#include "mconverter.h"
#include "LoUIClass/loemptydialog.h"
#include "usbdiskfuncdialog.h"
#include "usbdetectdialog.h"
#include <globaldefine.h>
#include "sendprogramdialog.h"
#include "mainwindow.h"

wProgramItem::wProgramItem(const QString &pRoot, const QString &name, int w, int h, const QString &remarks, LoQTreeWidget *parent,QWidget *pWnd) :
    QObject(parent),
    QTreeWidgetItem(UserType),
    m_parent(parent)
{
    m_name    = name;
    m_width   = w;
    m_height  = h;
    m_remarks = remarks;
    m_fsize   = 0;
    m_last    = QDateTime::currentDateTime();
    m_strSavePath = pRoot;
    m_strProgramItemPath   = pRoot + MACRO_FENGEFU + m_name;
    m_orgName = m_name;
    m_pWnd=pWnd;
    m_strConverSaveTmpPath=LoAppConfig::getInstance()->NProgramsLocation();
    init();
    emit sigEditProgram();

}

wProgramItem::wProgramItem(const QString &pRoot, const QJsonObject &json, LoQTreeWidget *parent,QWidget *pWnd) :
    QObject(parent),
    QTreeWidgetItem(UserType),
    m_parent(parent)
{
    m_name    = json["name"].toString();
    m_width   = json["resolution"]["w"].toInt();
    m_height  = json["resolution"]["h"].toInt();
    m_remarks = json["remarks"].toString();
    m_fsize   = json["file_size"].toDouble();
    m_last    = QDateTime::fromString(json["last_edit"].toString(), "yyyy-MM-dd hh:mm:ss");
    m_strSavePath = pRoot;
    m_strProgramItemPath   = pRoot + MACRO_FENGEFU + m_name;
    m_orgName = m_name;
    m_pWnd=pWnd;
    m_strConverSaveTmpPath=LoAppConfig::getInstance()->NProgramsLocation();
    init();
}
QString wProgramItem::GetBnName()
{
    return m_bnName->text();
}
void wProgramItem::init()
{
    auto cfg = LoAppTools::getInstance();
    setData(ENUM_PROGRAMLISTHEADERITEM_NAME, 0,m_name);
    setData(ENUM_PROGRAMLISTHEADERITEM_RESOLUTION, 0, QString("%1 x %2").arg(m_width).arg(m_height));
    if(m_fsize<=0)
        setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, cfg->convertFileSize((long long)100));
    else
        setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, cfg->convertFileSize(m_fsize));
    setData(ENUM_PROGRAMLISTHEADERITEM_LASTTIME, 0, m_last.toString("yyyy-MM-dd hh:mm:ss"));
    setTextAlignment(ENUM_PROGRAMLISTHEADERITEM_NAME, Qt::AlignLeft | Qt::AlignVCenter);
    for(int i=1; i<ENUM_PROGRAMLISTHEADERITEM_END; i++) {
        setTextAlignment(i, Qt::AlignCenter);
    }
    setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
    setCheckState(0, Qt::Unchecked);
    m_parent->insertTopLevelItem(0,this);

    m_bnName = new QPushButton(m_name);
    m_bnName->setProperty("ssType", "topList");
    m_bnName->setProperty("ssName", "itemName");
    m_bnName->setCursor(QCursor(Qt::PointingHandCursor));
    m_parent->setItemWidget(this, ENUM_PROGRAMLISTHEADERITEM_NAME, m_bnName);
    connect(m_bnName, SIGNAL(clicked()), this, SLOT(onEditProgram()));
    connect(this,SIGNAL(sigEditProgram()),this, SLOT(onEditProgram()));
    m_bnExport = new QPushButton();
    m_bnExport->setProperty("ssType", "progItemTool");
    m_bnExport->setProperty("ssName", "progExport");
    m_bnExport->setCursor(QCursor(Qt::PointingHandCursor));
    m_bnExport->setToolTip(tr("ExportButtonTip"));
    //bnExport->setToolTip(tr("Export this program to usb device"));
    m_parent->setItemWidget(this, ENUM_PROGRAMLISTHEADERITEM_USB_EXPORT, m_bnExport);
    connect(m_bnExport, SIGNAL(clicked()), this, SLOT(onUsbExportProgram()));

    m_bnSend = new QPushButton();
    m_bnSend->setProperty("ssType", "progItemTool");
    m_bnSend->setProperty("ssName", "progSend");
    m_bnSend->setCursor(QCursor(Qt::PointingHandCursor));
    m_bnSend->setToolTip(tr("SendButtonTip"));
    //bnSend->setToolTip(tr("Send this program to LED screen"));
    m_parent->setItemWidget(this, ENUM_PROGRAMLISTHEADERITEM_SEND, m_bnSend);
    connect(m_bnSend, SIGNAL(clicked()), this, SLOT(onSendProgram()));
}
void wProgramItem::refreshLable()
{
    m_bnExport->setToolTip(tr("ExportButtonTip"));
    m_bnSend->setToolTip(tr("SendButtonTip"));

}
QJsonObject wProgramItem::jRoot()
{
    QJsonObject oRoot;
    QJsonObject oSize;
    oRoot["name"]       = m_name;
    oSize["w"]          = m_width;
    oSize["h"]          = m_height;
    oRoot["resolution"] = oSize;
    oRoot["remarks"]    = m_remarks;
    oRoot["file_size"]  = m_fsize;
    oRoot["last_edit"]  = m_last.toString("yyyy-MM-dd hh:mm:ss");
 //   oRoot["validDate"]["isValid"]=false;
    return oRoot;
}
void wProgramItem::DeleteOtherFilesInDir()
{

}

void wProgramItem::save()
{
    QDir dRoot(m_strProgramItemPath);
    QDir dParent(m_strSavePath);
    if(!dRoot.exists()) {
        dParent.mkdir(m_name);
    } else if(m_name != m_orgName) {
        dParent.rename(m_orgName, m_name);
        m_orgName = m_name;
        m_strProgramItemPath = m_strSavePath + MACRO_FENGEFU + m_name;
    }

    dRoot = QDir(m_strProgramItemPath);
    if(dRoot.exists()) {
        QJsonDocument json(jRoot());
        QFile f(m_strProgramItemPath + MACRO_FENGEFU+"pro.json");
        f.open(QIODevice::WriteOnly);
        f.write(json.toJson());
        f.close();
    }
}

void wProgramItem::del()
{
    QDir dRoot(m_strProgramItemPath);
    if(dRoot.exists()) {
        dRoot.removeRecursively();
    }
}
//设置列表项的值
void wProgramItem::onSetProgram()
{
    auto cfg = LoAppTools::getInstance();
    m_bnName->setText(m_name);
    setData(ENUM_PROGRAMLISTHEADERITEM_RESOLUTION, 0, QString("%1 x %2").arg(m_width).arg(m_height));
    if(m_fsize<=0)
        setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, cfg->convertFileSize(100));
    else
        setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, cfg->convertFileSize(m_fsize));
    setData(ENUM_PROGRAMLISTHEADERITEM_LASTTIME, 0, m_last.toString("yyyy-MM-dd hh:mm:ss"));
    save();
}
//节目列表项的属性值改变后的响应槽函数
void wProgramItem::onAttrChanged()
{
    DeleteOtherFilesInDir();
    m_last = QDateTime::currentDateTime();
    m_fsize = dirFileSize(m_strProgramItemPath);
    onSetProgram();
}

void wProgramItem::onAttrChanged(const QString &name, int w, int h, const QString &remarks)
{
    m_name    = name;
    m_width   = w;
    m_height  = h;
    m_remarks = remarks;
    DeleteOtherFilesInDir();
    m_last    = QDateTime::currentDateTime();

    m_fsize = dirFileSize(m_strProgramItemPath);
    onSetProgram();
}

void wProgramItem::onEditProgram()
{
    wEditProgram *w = new wEditProgram(m_name, m_width, m_height, m_remarks, m_strProgramItemPath,m_strSavePath, m_parent);
    w->setAttribute(Qt::WA_DeleteOnClose);
    connect(w, SIGNAL(sProgramChanged()), this, SLOT(onAttrChanged()));//编辑窗口发送节目变化信号到该ITEM响应属性变化槽函数
    connect(w, SIGNAL(sProgramSaveAs(QString,QSize,QString)), m_pWnd, SLOT(onCreateNewProgramOnOpenEditProgramWidget(QString,QSize,QString)));//编辑窗口另存为按钮触发后发送信号到播放列表增加一行
    w->setWindowModality(Qt::WindowModal);//阻塞父窗口，所有祖先窗口及其子窗口
    w->show();
}

void wProgramItem::onUsbExportProgram()
{
    UsbDetectDialog * pDlg = new UsbDetectDialog(m_pWnd);
    connect(pDlg, SIGNAL(sigAcceptData(QString,QString)), this, SLOT(onUsbExportProgramPro(QString,QString)));
    if(pDlg->exec() == QDialog::Accepted)
    {


    }
//    UsbDiskFuncDialog * pDlg = new UsbDiskFuncDialog(m_pWnd);
//    connect(pDlg, SIGNAL(sigAcceptData(QString,QString)), this, SLOT(onUsbExportProgramPro(QString,QString)));
//    pDlg->SetPathDefault(LoAppConfig::getInstance()->NProgramsLocation());
//    if(pDlg->exec() == QDialog::Accepted)
//    {


//    }
}
void wProgramItem::onUsbExportProgramPro(QString strPath,QString strPassword)
{
    LoEmptyDialog * msgbox = new LoEmptyDialog(m_pWnd);
    QString strUsbProgramName=m_name;

    //strUsbProgramName=m_name;
    auto converter = new mConverter(strUsbProgramName,strPath,strPassword ,this);
    converter->m_usbZipFlag=1;
    //转换结束，发送信号触发converter释放内存
    connect(converter, SIGNAL(finished()),                  converter, SLOT(deleteLater()));
    connect(converter, SIGNAL(finished()),                  msgbox, SLOT(unlock()));
    connect(converter, SIGNAL(finished()),                  this, SLOT(UsbExportFinished()));
    //链接转换进度信号到进度条槽函数
    connect(converter, SIGNAL(sProgress(QString,int,bool)), msgbox->m_pIndicator,    SLOT(onProgress(QString,int,bool)));
    //链接进度对话框启动信号到转换开始槽函数
    connect(msgbox,    SIGNAL(startUp()),                   converter, SLOT(start()));
    connect(converter, SIGNAL(sigConvertTimerOut()), msgbox,    SLOT(TimerOutUnlock()));//显示正在保存提示对话框
    msgbox->lock(tr("Convertering")+"...",tr("USB Export Successed"),tr("USB Export TimeOut"));
    msgbox->exec();
}

void wProgramItem::onSendProgram()
{

    LoEmptyDialog * msgbox = new LoEmptyDialog(m_pWnd);
    //转换节目
    auto converter = new mConverter(m_name,m_strConverSaveTmpPath,"" ,this);
    converter->m_usbZipFlag=0;
    //转换结束，发送信号触发converter释放内存
    connect(converter, SIGNAL(finished()),                  converter, SLOT(deleteLater()));
    connect(converter, SIGNAL(finished()),                  msgbox, SLOT(unlock()));
    //链接转换进度信号到进度条槽函数
    connect(converter, SIGNAL(sProgress(QString,int,bool)), msgbox->m_pIndicator,    SLOT(onProgress(QString,int,bool)));
    //链接进度对话框启动信号到转换开始槽函数
    connect(msgbox,    SIGNAL(startUp()),                   converter, SLOT(start()));
    connect(converter, SIGNAL(sigConvertTimerOut()), msgbox,    SLOT(TimerOutUnlock()));//显示正在保存提示对话框
    msgbox->lock(tr("Convertering")+"...",tr("Converter Successed"),tr("Converter TimeOut"));
    msgbox->exec();

    SendProgramDialog *pDlg= new SendProgramDialog(m_pWnd,m_name,m_strConverSaveTmpPath);
    pDlg->exec();

//发送post命令，将任务发送到控制卡

//控制卡主动向指定的连接上报进度

}
