#include "cctrlfiledir.h"
#include <QDir>
#include "gui.h"
#include <QFont>
#include "cmakepath.h"
#include "logic.h"
#include <QMessageBox>
#include <QStyleFactory>
static void buildctrl(CCtrlFileDir* pCtrl,QTreeWidgetItem* parent,const QString&  filepath)
{
    QDir dir(filepath);
    foreach(QString file,dir.entryList(QDir::AllEntries|QDir::NoDotAndDotDot))
    {
        QFileInfo info=QFileInfo(dir,file);
		//MqDebug()<<info.path();
        if(info.isFile()&&info.suffix()==pCtrl->m_filters)
        {
            QTreeWidgetItem* pChild=new QTreeWidgetItem(parent,QStringList(file));
            pChild->setData(0, Qt::UserRole, CCtrlFileDir::ITEM_FILE);
            pChild->setIcon(0,pCtrl->IconData);
            parent->insertChild(0,pChild);
        }
        if(info.isDir())
        {
			CWorker* pWorker=GET_CHDIRECT(M_WORKER,CWorker);
			if(pWorker->m_workLevel<=LEVEL_OPERATOR){
				QString path = info.absoluteFilePath();
				if(path!=CMakePath::make_data_path("")){
					CGEMDriver* pDriverGEM=GET_CARD(GEM_DRIVER_JNG, CGEMDriver);
					QString operatorFolder = pDriverGEM->m_Variants.get_VData(Var_MES_RecipeRoot)->toString();
					QString folderPath = CMakePath::make_data_path(operatorFolder);
					if(path != folderPath){
						//MqDebug()<<"Skip Folder:"<<info.path();
						continue;
					}
				}
			}

			//MqDebug()<<"Create Folder"<<info.absoluteFilePath();
            QTreeWidgetItem* pChild=new QTreeWidgetItem(parent,QStringList(file));
            pChild->setData(0, Qt::UserRole, CCtrlFileDir::ITEM_DIR);
            pChild->setIcon(0,pCtrl->IconDir);
            parent->addChild(pChild);
            dir.cd(file);
            buildctrl(pCtrl,pChild,dir.absolutePath());
            dir.cdUp();
        }
    }
}

static void clearCtrl(CCtrlFileDir* pCtrl,QTreeWidgetItem* pItem)
{
    int32_t count = pItem->childCount();
    for(int32_t i=0; i<count; i++)
    {
        QTreeWidgetItem *pChild = pItem->child(0);
        clearCtrl(pCtrl,pChild);
    }
	//MqDebug() << "Clear:"<<pItem->text(0);
    QTreeWidgetItem* pParent=pItem->parent();
    if(pParent)
    {
        pParent->removeChild(pItem);
    }
    if(pCtrl->m_pRootItem!=pItem)
    {
		//MqDebug() << "Delete:"<<pItem->text(0);
        delete pItem;
    }
}
CCtrlFileDir::CCtrlFileDir(QWidget *parent)
    :QTreeWidget(parent)
{
    setStyle(QStyleFactory::create("windows"));
    IconRoot.addFile(CMakePath::make_bin_path("../theme/root.ico"));
    IconDir.addFile(CMakePath::make_bin_path("../theme/dir.ico"));
    IconData.addFile(CMakePath::make_bin_path("../theme/data.ico"));
    m_pRootItem=new QTreeWidgetItem(this,QStringList(trUtf8("Data")));
    m_pRootItem->setIcon(0,IconRoot);
    m_pSelItem=m_pRootItem;
    m_filters=FILE_FILTER;
    rootPath=CMakePath::make_data_path("");
    reBuildCtrl();
    connect(this,SIGNAL(currentItemChanged(QTreeWidgetItem * , QTreeWidgetItem * )),
            this,SLOT(MUpdateCtrl(QTreeWidgetItem * , QTreeWidgetItem * )));

}

void CCtrlFileDir::reBuildCtrl()
{
    clearCtrl(this,m_pRootItem);

    buildctrl(this,m_pRootItem,rootPath);
    MFresh();
}
static QString getItemRelPath(CCtrlFileDir* pCtrl,QTreeWidgetItem*  pItem,bool bpath=true)
{
    Q_ASSERT(pItem);
    QStringList list;
    QString path;
    while(pItem!=pCtrl->m_pRootItem)
    {
        list.push_front(pItem->text(0));
        pItem=pItem->parent();
    }
    if(!bpath)
    {
        list.removeLast();
    }
    bool bfirst=true;
    foreach(QString file,list)
    {
        if(bfirst)
        {
            bfirst=false;
            path=file;
        }
        else
        {
            path+="/"+file;
        }
    }
    return path;

}

QString CCtrlFileDir::GetSelRelPath()
{
    Q_ASSERT(m_pSelItem);
    return getItemRelPath(this,m_pSelItem);
}

QString CCtrlFileDir::GetSelRelDir()
{

    Q_ASSERT(m_pSelItem);
    return getItemRelPath(this,m_pSelItem,false);
}

QString CCtrlFileDir::GetSelFullPath()
{
    return  rootPath+"/"+GetSelRelPath();
}

QString CCtrlFileDir::GetRootPath()
{
    return rootPath;
}

static QTreeWidgetItem* findCtrl_item(CCtrlFileDir* pCtrl,
                                      QTreeWidgetItem*  parentItem,
                                      QString& relpath,
                                      bool bsetcolor)
{
    int32_t count = parentItem->childCount();
    for(int32_t i=0; i<count; i++)
    {
        QTreeWidgetItem *pChild = parentItem->child(i);
        if(pChild->data(0,Qt::UserRole)==CCtrlFileDir::ITEM_FILE)
        {
            QString temppath= getItemRelPath(  pCtrl,pChild);
            if(temppath==relpath )
            {
                if(bsetcolor)
                {
                    pChild->setBackgroundColor(0,Qt::darkBlue);
                    pChild->setForeground(0,Qt::white);
                }
                return pChild;
            }
        }
        else
        {
            QTreeWidgetItem* pitem=findCtrl_item(pCtrl,pChild,
                                                 relpath,bsetcolor);
            if(pitem) return pitem;
        }
        if(bsetcolor)
        {
            pChild->setBackgroundColor(0,Qt::white);
            pChild->setForeground(0,Qt::black);
        }
    }
    return 0;
}

void CCtrlFileDir::MFresh()
{

    m_pSelItem= findCtrl_item(this,m_pRootItem,m_gSystem.GetCurFile(),
                              false);

    if(m_pSelItem)
    {
       setCurrentItem(m_pSelItem);
       scrollToItem(m_pSelItem);
    }
    else
    {
        m_pSelItem=m_pRootItem;
    }
}

void CCtrlFileDir::MUpdateCtrl(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
    UNUSED(previous);
    m_pSelItem=current;
    MqDebug()<<GetSelFullPath();

}

