#include <stdio.h>
#include <stdlib.h>
#include <string.h>
                #include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "sthreadimagesave.h"

#include "mainwindow.h"
#include <QDir>
#include "formcapture.h"

#include "SDCMSendImpl.h"
#include "SDCMImage.h"
#include "cscallbacksendprogress.h"
#include <QDirIterator>
#include <QProcess>
#include <QDataStream>
#include <QFileDialog>
#include <QDateTime>
#include <QFileInfo>


SThreadImageSave::SThreadImageSave():QSThread()
{
    m_bDeferredInitMainWidget = false;
    m_pCURL = NULL;
    SCURL::Init();

    //m_pDatabase = NULL;



    /*
    m_nDetectOffsetX = 554;
    m_nDetectOffsetY = 76;
    m_nDetectWidth = 1064;
    m_nDetectHeight = 920;
    m_bDetectReady = false;
    m_pImageDetect = new uint8_t[1920*1080*3];
    m_nCurrentState = 0;

    m_bLoadImage = false;

    QString strPath = QDir::currentPath();

    QDir().mkdir("/data/image");
    QDir().mkdir("/data/video");

    #ifdef _SYOLOV5
    m_pDetectObject = new SYolov5;
    m_pDetectObject->Init("best.engine");
    #endif



    m_pImageTest = new QImage("test.png");

    *m_pImageTest = m_pImageTest->convertToFormat(QImage::Format_RGB888);
    */

    connect(&m_TimerMissBeep, SIGNAL(timeout()), this, SLOT(MissCaptureBeep()));

}

SThreadImageSave::~SThreadImageSave()
{

    disconnect(&m_TimerMissBeep, SIGNAL(timeout()), this, SLOT(MissCaptureBeep()));

    //SAFE_DELETE(m_pDatabase);


}

void SThreadImageSave::OpenDatabase()
{
    return;
    //m_pDatabase = new SDatabase;
    //m_pDatabase->OpenDatabase("/home/birdhead/test.db", true);
}

void SThreadImageSave::Init()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    int nVideoWidth = pCommonData->GetVideoWidth();
    int nVideoHeight = pCommonData->GetVideoHeight();

    m_bErrorSamba = false;
    m_nExportType = 0;
    m_bMissCapture = false;
    m_nDetectOffsetX = 554;
    m_nDetectOffsetY = 76;
    m_nDetectWidth = 1064;
    m_nDetectHeight = 920;
    m_bDetectReady = false;
    m_pImageDetect = new uint8_t[nVideoWidth*nVideoHeight*3];
    m_pImageDetectSrc = new uint8_t[nVideoWidth*nVideoHeight*3];
    m_nCurrentState = 0;

    m_bLoadImage = false;

    QString strPath = QDir::currentPath();

    QDir().mkdir("/data/image");
    QDir().mkdir("/data/video");

    #ifdef _SYOLOV5
    m_pDetectObject = new SYolov5;
    m_pDetectObject->Init("/home/birdhead/best.engine");
    //m_pDetectObject->Init("last.engine");
    #endif


    m_bCancelLoad = false;


    m_pImageTest = NULL;

    //m_pImageTest = new QImage("test.png");

    //*m_pImageTest = m_pImageTest->convertToFormat(QImage::Format_RGB888);


}


void SThreadImageSave::InnerRun()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    if(pCommonData==NULL)
    {
        usleep(1000);
        return;
    }

    if(m_nCurrentState&0x01)
    {
        SaveCaptureImage();
    }
    else if(m_nCurrentState&0x02)
    {
        SaveCaptureImage();
        //m_nCurrentState = 0;
    }
    else if(m_nCurrentState&0x08)
    {
        m_bCancelLoad = false;

        LoadHistoryImage();

        m_nCurrentState = 0;

    }

    if(m_nCurrentState&0x20)
    {
        SaveCaptureImageToFile();
        usleep(20*1000);
    }

    if(m_nCurrentState&0x80)
    {
        if(m_nExportType==0)
        {
            //ExportUSB();
            ExportUSB_mp4();
        }
        else if(m_nExportType==1)
        {
            ExportNetworkDirectory();
        }


        m_bExport = false;

        if(m_nCurrentState&0x80)
        {
            m_nCurrentState = (m_nCurrentState & ~0x80);
        }

    }

    if(m_nCurrentState&0x100)
    {
        CleanStorage();
        CompleteCleanStorage();
        m_nCurrentState = 0;
        m_bDeferredInitMainWidget = true;
    }

    else if(m_nCurrentState&0x200)
    {
        m_bCancelLoad = false;

        LoadAcquisitionFromHistory();

        m_nCurrentState = 0x2000;

    }
    else if(m_nCurrentState&0x400)
    {
        m_bExecuteUSBBackup = true;
        USBBackup();
        m_bExecuteUSBBackup = false;
    }


    if(m_nCurrentState&0x10)
    {
        if(m_bDetectReady==true)
        {
            m_LockDetect.lock();
            {
                MainWindow* pMainWindow = MainWindow::GetMainWindow();
                FormCapture* pFormCapture = (FormCapture*)pMainWindow->GetFormCapture();

                if(pCommonData->IsActiveDetect()==true)
                {
                    #ifdef _SYOLOV5
                    vector<YOLO_RESULT> listRect;
                    vector<QRect> listRectDisplay;

                    //uchar* pData = m_pImageTest->bits();
                    //listRect = m_pDetectObject->Detection(pData, 640, 640);
                    //listRect = m_pDetectObject->Detection(m_pImageDetect, 1920, 1080);

                    pCommonData->ConvertColor2(m_pImageDetectSrc, m_pImageDetect, m_nDetectOffsetX, m_nDetectOffsetY, m_nDetectWidth, m_nDetectHeight);

                    listRect = m_pDetectObject->Detection(m_pImageDetect, m_nDetectWidth, m_nDetectHeight, 0.15, 0.15);

                    if(listRect.size()>0)
                    {
                        int i=0;

                        float fRatioX = (float)m_nDetectWidth / 640.0f;
                        float fRatioY = (float)m_nDetectHeight / 640.0f;

                        for(i=0 ; i<listRect.size() ; i++)
                        {
                            YOLO_RESULT yr = listRect[i];

                            //if(yr.fClass>0)
                            {


                                //float fLeft = (yr.fCenterX - yr.fWidth/2)/640.0f * (float)m_nDetectWidth + m_nDetectOffsetX;
                                //float fTop = (yr.fCenterY - yr.fHeight/2)/640.0f * (float)m_nDetectHeight + m_nDetectOffsetY;
                                //float fWidth = (yr.fWidth)/640.0f * (float)m_nDetectWidth;
                                //float fHeight = (yr.fHeight)/640.0f * (float)m_nDetectHeight;

                                float fLeft = yr.fLeft + m_nDetectOffsetX;
                                float fTop = yr.fTop + m_nDetectOffsetY;
                                float fWidth = yr.fWidth;
                                float fHeight = yr.fHeight;

                                QRect rectDisplay = QRect((int)fLeft, (int)fTop, (int)fWidth, (int)fHeight);
                                //QRect rectTmp = QRect((int)fLeft, (int)fTop, (int)yr.fWidth, (int)yr.fHeight);
                                //QRect rectTmp = QRect((int)(yr.fLeft*fRatioX), (int)(yr.fTop*fRatioY), (int)(yr.fWidth*fRatioX), (int)(yr.fHeight*fRatioX));
                                //QRect rectDisplay = QRect((int)(rectTmp.x()+m_nDetectOffsetX), (int)(rectTmp.y()+m_nDetectOffsetY), (int)(rectTmp.width()), (int)(rectTmp.height()));

                                listRectDisplay.push_back(rectDisplay);
                            }


                        }
                    }


                    pFormCapture->UpdateObjectDisplay(listRectDisplay);
                    usleep(10);
                    #endif
                }
                else
                {
                    vector<QRect> listRectDisplay;
                    pFormCapture->UpdateObjectDisplay(listRectDisplay);
                }
                m_LockDetect.unlock();
                m_bDetectReady = false;
            }
        }


    }
    else
    {
        //usleep(100*1000);
        msleep(1);
    }





}

CAPTURE_IMAGE* SThreadImageSave::SetImageCapture(uint8_t* pImage, int nWidth, int nHeight)
{
    CommonData* pCommonData = MainWindow::GetCommonData();

    CAPTURE_IMAGE* pCaptureImage = NULL;
    pCaptureImage = pCommonData->AddCaptureImage(pImage, nWidth, nHeight, DISPLAY_IMAGE);

    m_nCurrentState = (m_nCurrentState | 0x01);

    return pCaptureImage;
}

CAPTURE_IMAGE* SThreadImageSave::SetVideoCapture(uint8_t* pImage, int nWidth, int nHeight)
{
    CommonData* pCommonData = MainWindow::GetCommonData();

    CAPTURE_IMAGE* pCaptureImage = NULL;
    pCaptureImage = pCommonData->AddCaptureImage(pImage, nWidth, nHeight, DISPLAY_VIDEO);

    m_nCurrentState = (m_nCurrentState | 0x02);

    return pCaptureImage;
}



/*
vector<WorklistResponseData>* SThreadImageSave::GetWorklistData()
{
    return m_pWorklistData;
}
*/

vector<CSDCM*>* SThreadImageSave::GetWorklistDump()
{
    return m_pDCMDumpList;
}



void SThreadImageSave::SaveCaptureImage()
{

    int i=0;
    bool bSaveFile = false;
    CommonData* pCommonData = MainWindow::GetCommonData();

    int nVideoWidth = pCommonData->GetVideoWidth();
    int nVideoHeight = pCommonData->GetVideoHeight();

    vector<CAPTURE_IMAGE*>* pListCaptureImage = pCommonData->GetListCaptureImage();
    {

        for(i=0 ; i<pListCaptureImage->size() ; i++)
        {
            CAPTURE_IMAGE* pCaptureImage = (*pListCaptureImage)[i];
            if(pCaptureImage->m_strImageFilename=="")
            {
                pCommonData->ReleaseListCaptureImage();
                pCommonData->ConvertCaptureImage(pCaptureImage, nVideoWidth, nVideoHeight);

                if(pCaptureImage->m_nType==DISPLAY_IMAGE)
                {
                    captureImage(pCaptureImage);
                }
                else
                {
                    captureVideo(pCaptureImage);
                }

                bSaveFile = true;
                break;
            }
        }
    }

    if(bSaveFile==false)
    {
        pCommonData->ReleaseListCaptureImage();
    }



    if(bSaveFile==false)
    {
        m_nCurrentState = (m_nCurrentState & ~0x20);
        usleep(30*1000);
    }
    else
    {
        m_nCurrentState = (m_nCurrentState | 0x20);
    }


    //m_nCurrentState = 5;
}



void SThreadImageSave::LoadHistoryImage()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    HISTORY_STUDY* pHistoryStudy = pCommonData->GetCurrentHistoryStudy();

    //int nStudyIndex = pCommonData->GetHistorySearchStudyIndex();

    if(pHistoryStudy==NULL)
    {
        pCommonData->ReleaseCurrentHistoryStudy();
        return;
    }

    m_bLoadImage = true;

    QString strStudyIndex = *pHistoryStudy->pStrStudyIndex;
    pCommonData->ReleaseCurrentHistoryStudy();

    int nStudyIndex = strStudyIndex.toInt();

    pCommonData->ClearHistoryImage();




    QList<QStringList> listResponse;
    QList<QStringList>::iterator it;

    //m_pDatabase->GetImageWithStudyIndex(nStudyIndex, listResponse);
    listResponse = m_ListImageWithStudy;



    //QList<QStringList*>* pResult = pDatabase->GetResult();

    int nTotalCount = listResponse.size();

    if(nTotalCount<=0)
    {
        listResponse.clear();
    }




    vector<ImageSelect*>* pListHistoryImage = pCommonData->GetListHistoryImage();

    QString strImageExtension = *pCommonData->GetImageExtension();

    QImage* pImageLoad = new QImage;
    int i=0;
    for(i=0 ; i<nTotalCount && m_bLoadImage==true && m_bCancelLoad==false ; i++)
    {
        QStringList listData = listResponse.at(i);

        QString strFile = listData.at(10);
        QString strFileType = listData.at(15);
        QString strDelete = listData.at(13);
        QString strSend = listData.at(14);
        QString strDate = listData.at(2);
        QString strTime = listData.at(3);
        QString strStudyInstanceUID = listData.at(4);
        QString strSeriesInstanceUID = listData.at(7);
        QString strImageInstanceUID = listData.at(11);
        QString strPatientAge = listData.at(22);
        int nImageNumber = listData.at(24).toInt();
        int nSeriesNumber = listData.at(5).toInt();


        int nImageIndex = listData.at(9).toInt();
        int nStudyIndex = listData.at(0).toInt();
        int nSeriesIndex = listData.at(8).toInt();
        int nPatientIndex = listData.at(1).toInt();

        bool bSend = (bool)strSend.toInt();
        bool bDelete = (bool)strDelete.toInt();
        //QImage* pImage = NULL;
        ImageSelect* pImageSelect = new ImageSelect;

        if(strFileType=="1")
        {
            pImageSelect->m_nType = DISPLAY_VIDEO;
            QString strFindImageFile = GetFindImageWithMovieFile(strFile);
            QString strFind;
            strFind = strFindImageFile + ".png";
            QFileInfo fi_png(strFind);
            if(fi_png.exists()==true)
            {
                pImageSelect->m_strFile = strFind;
            }
            else
            {
                strFind = strFindImageFile + ".jpg";
                QFileInfo fi_jpg(strFind);
                if(fi_jpg.exists()==true)
                {
                    pImageSelect->m_strFile = strFind;
                }
                else
                {
                    strFind = strFindImageFile + ".bmp";
                    QFileInfo fi_bmp(strFind);
                    if(fi_bmp.exists()==true)
                    {
                        pImageSelect->m_strFile = strFind;
                    }

                }

            }

            strFile = strFind;




        }
        else if(strFileType=="0")
        {
            pImageSelect->m_nType = DISPLAY_IMAGE;
        }

        pImageSelect->m_strDate = strDate;
        pImageSelect->m_strTime = strTime;

        {
            pImageLoad->load(strFile);
            int nWidth = pImageLoad->width()/2;
            int nHeight = pImageLoad->height()/2;

            QImage imageHalf = pImageLoad->scaled(nWidth, nHeight);

            if(imageHalf.format()!=QImage::Format_RGB888)
            {
#ifdef _PC
                imageHalf = imageHalf.convertToFormat(QImage::Format_RGB888);
#elif _XAVIER_NX
                imageHalf = imageHalf.convertToFormat(QImage::Format_RGB888);
#elif _JETSON_TX2_NX
                imageHalf = imageHalf.convertToFormat(QImage::Format_RGB888);
                //pImageLoad->convert(QImage::Format_RGB888);
#endif
            }

            int nFormat = (int)imageHalf.format();

            pImageSelect->CreateImage(nWidth, nHeight, nFormat);

            const uchar* pImageData = imageHalf.constBits();
            memcpy(pImageSelect->m_pImageData, pImageData, nWidth*nHeight*3);
        }


        //pImageSelect->m_pImage = pImage;
        pImageSelect->m_bSelect = true;
        pImageSelect->m_strFile = strFile;
        pImageSelect->m_bSend = bSend;
        pImageSelect->m_bDelete = bDelete;

        pImageSelect->m_strStudyInstanceUID = strStudyInstanceUID;
        pImageSelect->m_strSeriesInstanceUID = strSeriesInstanceUID;
        pImageSelect->m_strImageInstanceUID = strImageInstanceUID;

        pImageSelect->m_nImageNumber = nImageNumber;
        pImageSelect->m_nSeriesNumber = nSeriesNumber;

        pImageSelect->m_nIndexStudy = nStudyIndex;
        pImageSelect->m_nIndexSeries = nSeriesIndex;
        pImageSelect->m_nIndexImage = nImageIndex;
        pImageSelect->m_nIndexPatient = nPatientIndex;


        pImageSelect->m_strPatientAge = strPatientAge;

        pListHistoryImage->push_back(pImageSelect);


        SetImageLoadInfo(i, nTotalCount, pImageSelect);

        usleep(10*1000);
    }

    SAFE_DELETE(pImageLoad);

    pCommonData->ReleaseListHistoryImage();



    //SDatabase::DeleteListReponse(m_ListImageWithStudy);
    m_ListImageWithStudy.clear();


    if(m_bCancelLoad==false)
    {
        ImageLoadComplete();
    }

}



void SThreadImageSave::LoadAcquisitionFromHistory()
{
    CommonData* pCommonData = MainWindow::GetCommonData();

    QList<QStringList> listResponse;
    QList<QStringList>::iterator it;



    listResponse = m_ListImageWithStudy;
    //m_pDatabase->GetImageWithStudyIndexASC(nStudyIndex, listResponse);


    int nTotalCount = listResponse.size();






    vector<CAPTURE_IMAGE*>* pListCapture = pCommonData->GetListCaptureImage();

    int nCaptureCount = 0;
    nCaptureCount = pListCapture->size();
    pCommonData->ReleaseListCaptureImage();

    if(nCaptureCount==nTotalCount || nTotalCount<=0)
    {
        CompleteAcquisitionFromHistory();
        m_bLoadImage = false;
        return;
    }
    else
    {
        pCommonData->ClearHistoryImage();
        pCommonData->ClearCaptureImage();
    }

    pListCapture = pCommonData->GetListCaptureImage();

    m_bLoadImage = true;

    QImage* pImageLoad = new QImage;
    int i=0;
    for(i=0 ; i<nTotalCount && m_bLoadImage==true && m_bCancelLoad==false ; i++)
    {
        QStringList listData = listResponse.at(i);

        QString strFile = listData.at(10);
        QString strFileType = listData.at(15);
        QString strDelete = listData.at(13);
        QString strSend = listData.at(14);
        QString strDate = listData.at(2);
        QString strTime = listData.at(3);
        QString strAcquisitionNumber = listData.at(18);

        bool bSend = (bool)strSend.toInt();
        bool bDelete = (bool)strDelete.toInt();
        int nAcquisitionNumber = strAcquisitionNumber.toInt();
        //QImage* pImage = NULL;

        CAPTURE_IMAGE* pCaptureImage = new CAPTURE_IMAGE;
        pListCapture->push_back(pCaptureImage);

        pCaptureImage->m_nAcquisitionNumber = nAcquisitionNumber;

        if(strFileType=="1")
        {
            pCaptureImage->m_nType = DISPLAY_VIDEO;
            pCaptureImage->m_strVideoFilename = strFile;

            QString strFindImageFile = GetFindImageWithMovieFile(strFile);
            QString strFind;
            strFind = strFindImageFile + ".png";
            QFileInfo fi_png(strFind);
            if(fi_png.exists()==true)
            {
                pCaptureImage->m_strVideoFilename = strFind;
            }
            else
            {
                strFind = strFindImageFile + ".jpg";
                QFileInfo fi_jpg(strFind);
                if(fi_jpg.exists()==true)
                {
                    pCaptureImage->m_strVideoFilename = strFind;
                }
                else
                {
                    strFind = strFindImageFile + ".bmp";
                    QFileInfo fi_bmp(strFind);
                    if(fi_bmp.exists()==true)
                    {
                        pCaptureImage->m_strVideoFilename = strFind;
                    }
                }
            }

            strFile = strFind;
        }
        else if(strFileType=="0")
        {
            pCaptureImage->m_nType = DISPLAY_IMAGE;
        }

        pCaptureImage->m_strImageFilename = strFile;

        QString strDateTime = QString("%1%2").arg(strDate).arg(strTime);
        pCaptureImage->m_DateTime = QDateTime::fromString(strDateTime, "yyyyMMddHHmmss");

        //pCaptureImage->m_pImage = new QImage(pCaptureImage->m_strImageFilename);
        bool bImageLoad = pImageLoad->load(pCaptureImage->m_strImageFilename);

        if(bImageLoad==true)
        {
            int nWidth = pImageLoad->width();
            int nHeight = pImageLoad->height();

            //pCaptureImage->m_pImageSmall = new QImage;
            QImage imageScaled = pImageLoad->scaled(nWidth/4, nHeight/4);
            pCaptureImage->CreateImage(nWidth/4, nHeight/4, QImage::Format_RGB888);
            imageScaled = imageScaled.convertToFormat(QImage::Format_RGB888);
            uint8_t* pImageDataScaled = imageScaled.bits();
            memcpy(pCaptureImage->m_pImageData, pImageDataScaled, imageScaled.width()*imageScaled.height()*3);
        }

        pCaptureImage->m_bCheck = true;
        pCaptureImage->m_bSend = bSend;
        pCaptureImage->m_bDelete = bDelete;

        pCaptureImage->m_nIndex = i;
        pCaptureImage->m_bSaveFile = true;



        LoadInfoAcquisitionFromHistory(i+1, nTotalCount);

        usleep(10*1000);
    }

    SAFE_DELETE(pImageLoad);

    //SDatabase::DeleteListReponse(m_ListImageWithStudy);
    m_ListImageWithStudy.clear();

    pCommonData->ReleaseListCaptureImage();

    CompleteAcquisitionFromHistory();

    m_bLoadImage = false;
}


void SThreadImageSave::StopLoadImage()
{
    m_bLoadImage = false;
}

void SThreadImageSave::SaveCaptureImageToFile()
{
    return;
    m_LockImageSaveToFile.lock();
    m_bSaveImage = true;

    CommonData* pCommonData = MainWindow::GetCommonData();

    int i=0;
    int nExecCount = 0;
    int nImageCount = m_ListCaptureSaveToFile.size();
    //QElapsedTimer t1;
    //t1.start();
    for(i=0 ; i<nImageCount && m_nCurrentState&0x20 ; i++)
    {
        CAPTURE_IMAGE* pCaptureImage = m_ListCaptureSaveToFile[i];        
        if(pCaptureImage->m_bSaveFile==false && pCaptureImage->m_strImageFilename.size()>0)
        {
            if(pCaptureImage->m_pImage==NULL)
            {
                m_bSaveImage = false;
                m_LockImageSaveToFile.unlock();
                return;
            }
            //crop image
#ifdef _CROP
            *pCaptureImage->m_pImage = pCaptureImage->m_pImage->copy(QRect(242, 5, 1376, 992));
#endif

            pCommonData->WriteBitmapFile(pCaptureImage->m_strImageFilename, pCaptureImage->m_pImage);
            pCaptureImage->m_bSaveFile = true;
            SAFE_DELETE(pCaptureImage->m_pImage);
            SAFE_DELETE(pCaptureImage->m_pImageCaptureRaw);
            SAFE_ARRAY_DELETE(pCaptureImage->m_pImageCaptureColor);
            usleep(100);
            m_bSaveImage = false;
            nExecCount++;


            m_LockImageSaveToFile.unlock();
            return;

        }

        if((m_nCurrentState&0x20)==false)
        {
            m_bSaveImage = false;
            nExecCount++;
            m_LockImageSaveToFile.unlock();
            return;
        }
    }

    if(m_nCurrentState&0x20)
    {
        if(nExecCount==0)
        {
            usleep(10*1000);
        }
    }

    m_bSaveImage = false;

    m_LockImageSaveToFile.unlock();


}


void SThreadImageSave::AddCaptureSaveToFile(CAPTURE_IMAGE* pCaptureImage)
{
    m_LockImageSaveToFile.lock();
    m_ListCaptureSaveToFile.push_back(pCaptureImage);
    m_LockImageSaveToFile.unlock();
}

void SThreadImageSave::ClearCaptureSaveToFile()
{
    m_LockImageSaveToFile.lock();
    m_ListCaptureSaveToFile.clear();
    m_LockImageSaveToFile.unlock();
}

void SThreadImageSave::ExitCapture()
{
    m_nCurrentState = 0;

    while(m_bSaveImage==true)
    {
        usleep(100*1000);
    }

}

void SThreadImageSave::SetImageDetect(uint8_t* pImage, int nWidth, int nHeight)
{
#ifdef _SYOLOV5
    if((m_nCurrentState&0x10)==0)
    {
        return;
    }
    //554, 76 (1064, 920) : 1920x1080
    //277, 38 (532, 460) : 1280x720
    if(m_LockDetect.tryLock(100)==true)
    {
        if(m_bDetectReady==false)
        {
            CommonData* pCommonData = MainWindow::GetCommonData();

            memcpy(m_pImageDetectSrc, pImage, nWidth*nHeight*2);

            //pCommonData->ConvertColor2(pImage, m_pImageDetect, m_nDetectOffsetX, m_nDetectOffsetY, m_nDetectWidth, m_nDetectHeight);
            /*
            uint8_t* pImageColor = pCommonData->ConvertColor(pImage, nWidth, nHeight);
            //uint8_t* pImageColor = (uint8_t*)pImage;

            int i=0;
            for(i=0 ; i<m_nDetectHeight ; i++)
            {
                memcpy(&m_pImageDetect[m_nDetectWidth*3*i], &pImageColor[1920*3*(i+m_nDetectOffsetY)+m_nDetectOffsetX*3], m_nDetectWidth*3);
            }
            usleep(1);

            //FILE* pFile = fopen("/home/birdhead/test.data", "wb");
            //fwrite(m_pImageDetect, m_nDetectWidth*m_nDetectHeight*3, 1, pFile);
            //fflush(pFile);
            //fclose(pFile);

            //memcpy(m_pImageDetect, pImageColor, nWidth*nHeight*3);
            */
            m_bDetectReady = true;
        }

        m_LockDetect.unlock();
    }
    else
    {
        usleep(100);
    }
#endif
}


void SThreadImageSave::SendImage(vector<QString> listFile)
{
    WRITE_FUNCTION_LOG();
    while(m_LockSendList.tryLock(100)==false)
    {
        usleep(100);
    }
    //m_LockSendList.lock();
    if(m_nCurrentState & 0x40)
    {
        int i=0;
        for(i=0 ; i<listFile.size() ; i++)
        {
            QString strFile = listFile[i];
            m_ListSendFileWait.push_back(strFile);
        }
    }
    else
    {
        //m_ListSendFile.clear();

        m_ListSendFile = listFile;

        m_nCurrentState = (m_nCurrentState | 0x40);
    }
    m_LockSendList.unlock();

    //m_nCurrentState = 6;
}


void SThreadImageSave::StartExport(int nType)
{
    m_nExportType = nType;
    m_bExport = true;

    m_nCurrentState = 0x80;

}

void SThreadImageSave::StopExport()
{
    m_bExport = false;
    if(m_nExportType==1)
    {
        if(m_nCurrentState&0x80)
        {
            m_LockExport.lock();
            if(m_pCURL!=NULL)
            {
                m_pCURL->StopCURL();
            }
            m_LockExport.unlock();
        }

        while(m_nCurrentState&0x80)
        {
            usleep(100*1000);
        }


    }

    m_nCurrentState = 0;
}

void SThreadImageSave::ExportUSB()
{
    if(m_bExport==false)
    {
        return;
    }

    SetExportInit();

    QFileInfo fileDevice("/dev/sda1");
    if(fileDevice.exists()==false)
    {
        return;
    }

    CommonData* pCommonData = MainWindow::GetCommonData();
    vector<QString>* pListExport = pCommonData->GetExportList();

    //QString strDestDirectory = "/home/birdhead/test";
    QString strDestDirectory = "/home/birdhead/backup";

    QDirIterator it(strDestDirectory, QDirIterator::Subdirectories);
    qint64 total = 0;

    while(it.hasNext()==true)
    {
        it.next();
        QFileInfo fi = it.fileInfo();
        if(fi.isDir()==true && fi.isSymLink()==false && fi.isAbsolute()==true)
        {
            QString strFilenameTmp = fi.fileName();
            if(strFilenameTmp=="." || strFilenameTmp=="..")
            {
                continue;
            }
            strDestDirectory = fi.filePath();
            break;
        }

    }

    if(strDestDirectory.size()==0)
    {
        return;
    }

    QDir dirDeleteImage(strDestDirectory+"/image");
    if(dirDeleteImage.exists()==true)
    {
        dirDeleteImage.removeRecursively();
    }

    QDir dirDeleteVideo(strDestDirectory+"/video");
    if(dirDeleteVideo.exists()==true)
    {
        dirDeleteVideo.removeRecursively();
    }

    QProcess::execute("sync");


    QString* pStrExternalDiskPath = pCommonData->GetExternalDiskPath();

    //strDestDirectory = "/home/birdhead/test";

    if(pStrExternalDiskPath->size()>0)
    {
        strDestDirectory = *pStrExternalDiskPath;
    }

    int i=0;
    for(i=0 ; i<pListExport->size() && m_bExport==true ; i++)
    {
        QString strFile = (*pListExport)[i];
        SetProgressExportFile(i+1, pListExport->size());

        QStringList listParse = strFile.split('/');

        QString strType = listParse[2];
        QString strStudyDate = listParse[3];
        QString strPatientID = listParse[4];
        QString strFilename = listParse[5];

        QString strDestFile = QString("%1/%2/%3/%4/%5").arg(strDestDirectory).arg(strType).arg(strStudyDate).arg(strPatientID).arg(strFilename);

        CheckAndCreateDir(strDestDirectory + "/" + strType);
        CheckAndCreateDir(strDestDirectory + "/" + strType + "/" + strStudyDate);
        CheckAndCreateDir(strDestDirectory + "/" + strType + "/" + strStudyDate + "/" + strPatientID);

        QStringList strListFile;

        if(strFilename.contains(MOVIE_FILE_EXTENSION)==true)
        {
            QString strFindFilename = strFilename;
            strFindFilename.remove(MOVIE_FILE_EXTENSION);
            QRegExp separator("_");
            QStringList listDataFilename = strFindFilename.split(separator);

            QString strCaptureIndex;
            QString strCaptureTime;

            int nDataSize = listDataFilename.size();
            if(nDataSize>0)
            {
                strCaptureIndex = listDataFilename[0];
            }
            if(nDataSize>1)
            {
                strCaptureTime = listDataFilename[1];
            }

            strFindFilename = QString("%1_%2").arg(strCaptureIndex).arg(strCaptureTime);
            qDebug() << strFilename << ": " << strFindFilename;

            QString strFindDirectory = QString("/data/video/%1/%2").arg(strStudyDate).arg(strPatientID);

            QDirIterator it(strFindDirectory, QDirIterator::Subdirectories);
            qint64 total = 0;

            while(it.hasNext()==true)
            {
                it.next();
                QFileInfo fi = it.fileInfo();
                if(fi.isFile()==true && fi.isSymLink()==false && fi.isAbsolute()==true)
                {
                    QString strTmpFile = fi.fileName();
                    if(strTmpFile.contains(MOVIE_FILE_EXTENSION) && strTmpFile.contains(strFindFilename)==true)
                    {
                        strDestFile = QString("%1/%2").arg(strFindDirectory).arg(strTmpFile);
                        strListFile.push_back(strDestFile);
                    }
                }

            }

        }
        else
        {
            strListFile.push_back(strFile);
        }

        int nIter = 0;
        for(nIter = 0 ; nIter<strListFile.size() ; nIter++)
        {
            strFile = strListFile[nIter];
            QFile fileRead(strFile);

            if(strDestFile.contains(MOVIE_FILE_EXTENSION)==true)
            {
            }

            if(fileRead.open(QIODevice::ReadOnly)==true)
            {
                qint64 nLength = fileRead.size();

                int nTotalCount = nLength / 4096;
                int nCurrentCount = 0;

                QStringList listParse = strFile.split('/');

                QString strType = listParse[2];
                QString strStudyDate = listParse[3];
                QString strPatientID = listParse[4];
                QString strFilename = listParse[5];

                QString strDestFile = QString("%1/%2/%3/%4/%5").arg(strDestDirectory).arg(strType).arg(strStudyDate).arg(strPatientID).arg(strFilename);

                //qDebug() << strDestFile;

                QFile fileWrite(strDestFile);

                if(fileWrite.exists()==true)
                {
                    fileWrite.remove();
                }
                char* pData = new char[4096];
                if(fileWrite.open(QIODevice::WriteOnly | QIODevice::NewOnly)==true)
                {
                    qint64 nRead = 0;
                    qint64 nReadTotal = 0;

                    while(nLength>nReadTotal && m_bExport==true)
                    {
                        SetProgressExportPercent(nCurrentCount+1, nTotalCount);

                        memset(pData, 0, sizeof(char)*4096);
                        nRead = fileRead.read(pData, 4096);
                        nReadTotal += nRead;
                        if(nRead>0)
                        {
                            fileWrite.write(pData, nRead);
                        }
                        else
                        {
                            break;
                        }

                        nCurrentCount++;
                    }

                    if(m_bExport==true)
                    {
                        fileWrite.flush();
                        fileWrite.close();
                    }
                    else
                    {

                    }

                }
                else
                {

                }

                fileRead.close();

                delete[] pData;

                SetProgressSync(false);

                if(m_bExport==true)
                {
                    QString strSync = QString("sync --data %1").arg(strDestFile);
                    //QProcess::execute(strSync);
                }
                else
                {

                }

                SetProgressSync(true);

            }
        }


    }

    SetExportComplete();
    m_bExport = false;
    return;


    SetProgressSync(false);
    if(m_bExport==true)
    {
        //QString strSync = QString("sync --data %1").arg(strDestDirectory);
        //QProcess::execute(strSync);

        QProcess::execute("sync");
    }
    SetProgressSync(true);


}



void SThreadImageSave::ExportUSB_mp4()
{
    if(m_bExport==false)
    {
        return;
    }

    SetExportInit();

    QFileInfo fileDevice("/dev/sda1");
    if(fileDevice.exists()==false)
    {
        return;
    }

    CommonData* pCommonData = MainWindow::GetCommonData();
    vector<QString>* pListExport = pCommonData->GetExportList();

    //QString strDestDirectory = "/home/birdhead/test";
    QString strDestDirectory = "/home/birdhead/backup";

    QDirIterator it(strDestDirectory, QDirIterator::Subdirectories);
    qint64 total = 0;

    while(it.hasNext()==true)
    {
        it.next();
        QFileInfo fi = it.fileInfo();
        if(fi.isDir()==true && fi.isSymLink()==false && fi.isAbsolute()==true)
        {
            QString strFilenameTmp = fi.fileName();
            if(strFilenameTmp=="." || strFilenameTmp=="..")
            {
                continue;
            }
            strDestDirectory = fi.filePath();
            break;
        }

    }

    if(strDestDirectory.size()==0)
    {
        return;
    }

    QDir dirDeleteImage(strDestDirectory+"/image");
    if(dirDeleteImage.exists()==true)
    {
        dirDeleteImage.removeRecursively();
    }

    QDir dirDeleteVideo(strDestDirectory+"/video");
    if(dirDeleteVideo.exists()==true)
    {
        dirDeleteVideo.removeRecursively();
    }

    QProcess::execute("sync");


    QString* pStrExternalDiskPath = pCommonData->GetExternalDiskPath();

    //strDestDirectory = "/home/birdhead/test";

    if(pStrExternalDiskPath->size()>0)
    {
        strDestDirectory = *pStrExternalDiskPath;
    }

    int i=0;
    for(i=0 ; i<pListExport->size() && m_bExport==true ; i++)
    {
        QString strFile = (*pListExport)[i];
        SetProgressExportFile(i+1, pListExport->size());

        QStringList listParse = strFile.split('/');

        QString strType = listParse[2];
        QString strStudyDate = listParse[3];
        QString strPatientID = listParse[4];
        QString strFilename = listParse[5];

        QString strDestFile = QString("%1/%2/%3/%4/%5").arg(strDestDirectory).arg(strType).arg(strStudyDate).arg(strPatientID).arg(strFilename);

        CheckAndCreateDir(strDestDirectory + "/" + strType);
        CheckAndCreateDir(strDestDirectory + "/" + strType + "/" + strStudyDate);
        CheckAndCreateDir(strDestDirectory + "/" + strType + "/" + strStudyDate + "/" + strPatientID);

        QStringList strListFile;
        {
            strListFile.push_back(strFile);
        }

        int nIter = 0;
        for(nIter = 0 ; nIter<strListFile.size() ; nIter++)
        {
            strFile = strListFile[nIter];
            QFile fileRead(strFile);
            if(fileRead.open(QIODevice::ReadOnly)==true)
            {
                qint64 nLength = fileRead.size();

                int nTotalCount = nLength / 4096;
                int nCurrentCount = 0;

                QStringList listParse = strFile.split('/');

                QString strType = listParse[2];
                QString strStudyDate = listParse[3];
                QString strPatientID = listParse[4];
                QString strFilename = listParse[5];

                QString strDestFile = QString("%1/%2/%3/%4/%5").arg(strDestDirectory).arg(strType).arg(strStudyDate).arg(strPatientID).arg(strFilename);

                //qDebug() << strDestFile;

                QFile fileWrite(strDestFile);

                if(fileWrite.exists()==true)
                {
                    fileWrite.remove();
                }
                char* pData = new char[4096];
                if(fileWrite.open(QIODevice::WriteOnly | QIODevice::NewOnly)==true)
                {
                    qint64 nRead = 0;
                    qint64 nReadTotal = 0;

                    while(nLength>nReadTotal && m_bExport==true)
                    {
                        SetProgressExportPercent(nCurrentCount+1, nTotalCount);

                        memset(pData, 0, sizeof(char)*4096);
                        nRead = fileRead.read(pData, 4096);
                        nReadTotal += nRead;
                        if(nRead>0)
                        {
                            fileWrite.write(pData, nRead);
                        }
                        else
                        {
                            break;
                        }

                        nCurrentCount++;
                    }

                    if(m_bExport==true)
                    {
                        fileWrite.flush();
                        fileWrite.close();
                    }
                    else
                    {

                    }

                }
                else
                {

                }

                fileRead.close();

                delete[] pData;




                if(m_bExport==true && strDestFile.contains(MOVIE_FILE_EXTENSION)==true)
                {
                    SetProgressSync(false);
                    QString strSync = QString("sync --data %1").arg(strDestFile);
                    QProcess::execute(strSync);
                    SetProgressSync(true);
                }
                else
                {

                }



            }
        }


    }

    pListExport->clear();

    SetExportComplete();
    m_bExport = false;
    return;


    SetProgressSync(false);
    if(m_bExport==true)
    {
        QString strSync = QString("sync --data %1").arg(strDestDirectory);
        QProcess::execute(strSync);

        QProcess::execute("sync");
    }
    SetProgressSync(true);


}



void SThreadImageSave::ExportNetworkDirectory()
{
    if(m_bExport==false || m_bErrorSamba==true)
    {
        SetExportComplete();
        /*m_bExport = false;*/
        return;
    }

    SetExportInit();

    /*
     * //Mount device check !!!!!!!!!!!!!!!!!!!!
    QFile fileDevice("/dev/sda1");
    if(fileDevice.exists()==false)
    {
        return;
    }
    */

    CommonData* pCommonData = MainWindow::GetCommonData();
    vector<QString>* pListExport = pCommonData->GetExportList();

    QString strDestDirectory = "/home/birdhead/samba";

    /*


    QDirIterator it(strDestDirectory, QDirIterator::Subdirectories);
    qint64 total = 0;

    while(it.hasNext()==true)
    {
        it.next();
        QFileInfo fi = it.fileInfo();
        if(fi.isDir()==true && fi.isSymLink()==false && fi.isAbsolute()==true)
        {
            QString strFilenameTmp = fi.fileName();
            if(strFilenameTmp=="." || strFilenameTmp=="..")
            {
                continue;
            }
            strDestDirectory = fi.filePath();
            break;
        }

    }

    if(strDestDirectory.size()==0)
    {
        return;
    }

    QDir dirDeleteImage(strDestDirectory+"/image");
    if(dirDeleteImage.exists()==true)
    {
        dirDeleteImage.removeRecursively();
    }

    QDir dirDeleteVideo(strDestDirectory+"/video");
    if(dirDeleteVideo.exists()==true)
    {
        dirDeleteVideo.removeRecursively();
    }

    QProcess::execute("sync");

    strDestDirectory = "/home/birdhead/samba";

    if(pStrExternalDiskPath->size()>0)
    {
        strDestDirectory = *pStrExternalDiskPath;
    }
    */


    QString* pStrExternalDiskPath = pCommonData->GetExternalDiskPath();




    SAFE_DELETE(m_pCURL);
    m_pCURL = new SCURL;
    connect(m_pCURL, SIGNAL(SetProgressExportPercent(quint64, quint64)), this, SLOT(SetProgressExportPercentSlot(quint64, quint64)));

    int i=0;
    for(i=0 ; i<pListExport->size() && m_bExport==true ; i++)
    {
        QString strFile = (*pListExport)[i];




        SetProgressExportFile(i+1, pListExport->size());


        QStringList listParse = strFile.split('/');

        QString strType = listParse[2];
        //QString strType = "cystoscopy";
        QString strStudyDate = listParse[3];
        QString strPatientID = listParse[4];
        QString strFilename = listParse[5];

        QString strDestFile = QString("%1/%2/%3/%4/%5").arg(strDestDirectory).arg(strType).arg(strStudyDate).arg(strPatientID).arg(strFilename);

        CheckAndCreateDir(strDestDirectory + "/" + strType);
        CheckAndCreateDir(strDestDirectory + "/" + strType + "/" + strStudyDate);
        CheckAndCreateDir(strDestDirectory + "/" + strType + "/" + strStudyDate + "/" + strPatientID);

        QStringList strListFile;

        if(strFilename.contains(MOVIE_FILE_EXTENSION)==true)
        {
            QString strFindFilename = strFilename;
            strFindFilename.remove(MOVIE_FILE_EXTENSION);

            QString strFindDirectory = QString("/data/video/%1/%2").arg(strStudyDate).arg(strPatientID);

            QDirIterator it(strFindDirectory, QDirIterator::Subdirectories);
            qint64 total = 0;

            while(it.hasNext()==true)
            {
                it.next();
                QFileInfo fi = it.fileInfo();
                if(fi.isFile()==true && fi.isSymLink()==false && fi.isAbsolute()==true)
                {
                    QString strTmpFile = fi.fileName();
                    if(strTmpFile.contains(MOVIE_FILE_EXTENSION) && strTmpFile.contains(strFindFilename)==true)
                    {
                        strDestFile = QString("%1/%2").arg(strFindDirectory).arg(strTmpFile);
                        strListFile.push_back(strDestFile);
                    }
                }

            }

        }
        else
        {
            strListFile.push_back(strFile);
        }

        int nIter = 0;



        bool bUseSamba = false;
        for(nIter = 0 ; nIter<strListFile.size() ; nIter++)
        {
            strFile = strListFile[nIter];

            if(bUseSamba==false)
            {
                QFileInfo fi(strFile);
                int nFileSize = fi.size();

                if(m_pCURL!=NULL)
                {
                    m_pCURL->UploadFTP(strFile);
                }




            }
            else
            {
                QFile fileRead(strFile);

                if(strDestFile.contains(".mkv")==true)
                {

                }

                if(fileRead.open(QIODevice::ReadOnly)==true)
                {
                    qint64 nLength = fileRead.size();

                    int nTotalCount = nLength / 4096;
                    int nCurrentCount = 0;

                    QStringList listParse = strFile.split('/');

                    QString strType = listParse[2];
                    QString strStudyDate = listParse[3];
                    QString strPatientID = listParse[4];
                    QString strFilename = listParse[5];

                    QString strDestFile = QString("%1/%2/%3/%4/%5").arg(strDestDirectory).arg(strType).arg(strStudyDate).arg(strPatientID).arg(strFilename);

                    //qDebug() << strDestFile;


                    QFile fileWrite(strDestFile);

                    if(fileWrite.exists()==true)
                    {
                        fileWrite.remove();
                    }
                    char* pData = new char[4096];
                    if(fileWrite.open(QIODevice::WriteOnly | QIODevice::NewOnly | QIODevice::Unbuffered)==true)
                    {
                        qint64 nRead = 0;
                        qint64 nReadTotal = 0;

                        while(nLength>nReadTotal && m_bExport==true)
                        {
                            SetProgressExportPercent(nCurrentCount+1, nTotalCount);

                            memset(pData, 0, sizeof(char)*4096);
                            nRead = fileRead.read(pData, 4096);
                            nReadTotal += nRead;
                            int nWrite = 0;
                            if(nRead>0)
                            {
                                if(fileWrite.isWritable()==true)
                                {
                                    nWrite = fileWrite.write(pData, nRead);
                                    if(nRead!=nWrite)
                                    {

                                    }
                                }
                                else
                                {

                                }

                            }
                            else
                            {
                                break;
                            }

                            nCurrentCount++;
                            if(nCurrentCount%100==0)
                            //if(nCurrentCount>0)
                            {
                                while(fileWrite.flush()==false)
                                {
                                    //QThread::msleep(10);



                                }
                                int nRet = 0;
                                nRet = fsync(fileWrite.handle());
                                if(nRet<0)
                                {
                                    fileWrite.close();
                                    SetExportComplete();
                                    /*m_bExport = false;*/
                                    m_bErrorSamba = true;
                                    return;
                                }

                            }
                        }
                        fileWrite.flush();
                        fileWrite.close();
                    }
                    else
                    {
                        //Network Error
                        SetExportComplete();
                        /*m_bExport = false;*/
                        m_bErrorSamba = true;
                        return;
                    }

                    fileRead.close();

                    delete[] pData;


                    SetProgressSync(false);
                    QString strSync = QString("sync -f %1").arg(strDestFile);
                    QProcess::execute(strSync);
                    SetProgressSync(true);

                }

            }
        }



    }

    disconnect(m_pCURL, SIGNAL(SetProgressExportPercent(quint64, quint64)), this, SLOT(SetProgressExportPercentSlot(quint64, quint64)));

    m_LockExport.lock();
    SAFE_DELETE(m_pCURL);
    m_LockExport.unlock();



    SetExportComplete();
    m_bExport = false;
    return;


    SetProgressSync(false);
    if(m_bExport==true)
    {
        //QString strSync = QString("sync --data %1").arg(strDestDirectory);
        //QProcess::execute(strSync);

        //QProcess::execute("sync");
    }
    SetProgressSync(true);


}

void SThreadImageSave::CheckAndCreateDir(QString strDir)
{
    QDir dir(strDir);
    if(dir.exists()==false)
    {
        dir.mkdir(strDir);
    }
}




void SThreadImageSave::CancelLoad()
{
    m_bCancelLoad = true;
}

void SThreadImageSave::CleanStorage()
{
    bool bDeleteAuto = true;

    //usleep(1000*1000*5);

    CommonData* pCommonData = MainWindow::GetCommonData();

    pCommonData->ComputeStorageSize();
    int nStorage = pCommonData->GetStorageSize();

    int nStorageSize = pCommonData->GetStorageSize();
    int nStorageFreeSize = pCommonData->GetStorageFreeSize();

    if(bDeleteAuto==true)
    {
        int i=0;
        {
            QDir directory("Log");
            //QDateTime dtCurrent = QDateTime::currentDateTime();
            QDateTime dtCheck = QDateTime::currentDateTime(); //dtCurrent.addDays(-14);
            QStringList listLogFile = directory.entryList(QStringList() << "*.log" << "*.LOG",QDir::Files);
            foreach(QString filename, listLogFile) {
                //do whatever you need to do
                int nYear = 0;
                int nMonth = 0;
                int nDay = 0;

                QString strYear;
                QString strMonth;
                QString strDay;

                strYear = filename.mid(0, 4);
                strMonth = filename.mid(4, 2);
                strDay = filename.mid(6, 2);

                nYear = strYear.toInt();
                nMonth = strMonth.toInt();
                nDay = strDay.toInt();

                QDate dtFile(nYear, nMonth, nDay);

                int nDayCheck = dtFile.daysTo(dtCheck.date());


                if(nDayCheck>60)
                {
                    QFile::remove("Log/"+filename);
                }

            }
        }


        //QList<QStringList*>* pResult = m_pDatabase->GetScheduledDeleteStudyDateList();

        QList<QStringList> result = m_ListScheduledDeleteStudyDateList;

        int nData = result.size();

        QString strStorageDirectory = "/data";

        for(i=0 ; i<nData ; i++)
        {
            QStringList listData = result[i];
            QString strDeleteStudyDate = listData[0];

            //Delete Image Directory
            {
                QString strDeletePath = QString("%1/image/%2").arg(strStorageDirectory).arg(strDeleteStudyDate);

                QDir dirDirectory(strDeletePath);
                if(dirDirectory.exists()==true)
                {
                    dirDirectory.removeRecursively();
                }
            }

            //Delete Video Directory
            {
                QString strDeletePath = QString("%1/video/%2").arg(strStorageDirectory).arg(strDeleteStudyDate);

                QDir dirDirectory(strDeletePath);
                if(dirDirectory.exists()==true)
                {
                    dirDirectory.removeRecursively();
                }
            }


            //pDatabase->SetDeleteStorageFile(strFileLocation);


        }
    }
}



void SThreadImageSave::MissCapture()
{
    m_nMissCount = 0;
    m_bMissCapture = true;    

    //MainWindow::GetMainWindow()->ViewDialogMissCapture();
    if(m_bDeferredInitMainWidget==true)
    {
        ViewDialogMissCapture();

        //MainWindow::GetCommonData()->Beep(true);
        m_TimerMissBeep.start(500);
    }



}

void SThreadImageSave::ClearMissCapture()
{
    m_bMissCapture = false;
    m_nMissCount = 0;

    m_TimerMissBeep.stop();
    MainWindow::GetCommonData()->Beep(false);
}

void SThreadImageSave::MissCaptureBeep()
{
    if(m_bMissCapture==true)
    {
        if(m_nMissCount%2==0)
        {
            MainWindow::GetCommonData()->Beep(true);
        }
        else
        {
            MainWindow::GetCommonData()->Beep(false);
        }

        m_nMissCount++;
    }
}

void SThreadImageSave::SetProgressExportPercentSlot(quint64 nCurrent, quint64 nTotal)
{
    SetProgressExportPercent(nCurrent, nTotal);
}


QString SThreadImageSave::GetFindImageWithMovieFile(const QString strMovieFile)
{
    QFileInfo file_info(strMovieFile);
    QString strPath = file_info.path();
    QString strFilename = file_info.fileName();
    strFilename.replace(MOVIE_FILE_EXTENSION, "");
    QRegExp separator("_");
    QStringList listData = strFilename.split(separator);
    QString strCaptureIndex;
    QString strCaptureTime;
    QString strCaptureIndex_Additional;
    QString strFindImage;

    strFindImage = strPath;
    strFindImage += "/";

    int nDataSize = listData.size();
    if(nDataSize>0)
    {
        strCaptureIndex = listData[0];
        if(strCaptureIndex.size()>0)
        {
            strFindImage += strCaptureIndex;
        }
    }
    if(nDataSize>1)
    {
        strCaptureTime = listData[1];
        if(strCaptureTime.size()>0)
        {
            strFindImage += "_";
            strFindImage += strCaptureTime;
        }
    }
    if(nDataSize>2)
    {
        strCaptureIndex_Additional = listData[2];
        if(strCaptureIndex_Additional.size()>0)
        {
            //strFindImage += "_";
            //strFindImage += strCaptureIndex_Additional;
        }
    }

    return strFindImage;
}


void SThreadImageSave::SetListImageWithStudy(const QList<QStringList> list)
{
    int i=0;
    m_ListImageWithStudy.clear();

    for(i=0 ; i<list.size() ; i++)
    {
        QStringList listData = list[i];
        QStringList listNewData = listData;
        m_ListImageWithStudy.push_back(listNewData);
    }
    //m_ListImageWithStudy = list;
}

void SThreadImageSave::SetListImageWithStudyASC(const QList<QStringList> list)
{
    int i=0;
    m_ListImageWithStudy.clear();

    for(i=0 ; i<list.size() ; i++)
    {
        QStringList listData = list[i];
        QStringList listNewData = listData;
        m_ListImageWithStudy.push_back(listNewData);
    }
    //m_ListImageWithStudy = list;
}


void SThreadImageSave::SetSchduledDeleteStudyDateList(const QStringList& list)
{
    int i=0;
    m_ListScheduledDeleteStudyDateList.clear();

    for(i=0 ; i<list.size() ; i++)
    {
        QString listDate = list[i];
        QStringList listNewData;
        listNewData.push_back(listDate);
        m_ListScheduledDeleteStudyDateList.push_back(listNewData);
    }
}

void SThreadImageSave::USBBackupInner()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    int i=0;
    int j=0;

    QStringList listBackup;
    vector<CAPTURE_IMAGE*>* pListCapture = pCommonData->GetListCaptureImage();
    {

        for(i=0 ; i<pListCapture->size() ; i++)
        {
            CAPTURE_IMAGE* pCaptureImage = (*pListCapture)[i];
            if(pCaptureImage->IsBackup()==false)
            {
                if(pCaptureImage->m_strImageFilename.size()>0 && pCaptureImage->m_nIndex>=0)
                {
                    listBackup.push_back(pCaptureImage->m_strImageFilename);
                }
            }
        }

    }
    pCommonData->ReleaseListCaptureImage();


    for(i=0 ; i<listBackup.size() ; i++)
    {
        QString strFilebackup = listBackup[i];

        QFileInfo fileInfo(strFilebackup);
        QString strPath = fileInfo.filePath();
        QString strFilename = fileInfo.fileName();

        QStringList listPath = strPath.split("/");
        QString strDate = listPath[3];
        QString strPatientID = listPath[4];

        QString strDest = QString("/home/birdhead/backup/image_backup/%1/%2/%3").arg(strDate).arg(strPatientID).arg(strFilename);


        CheckAndCreateDir("/home/birdhead/backup");
        CheckAndCreateDir("/home/birdhead/backup/image_backup/");
        CheckAndCreateDir(QString("/home/birdhead/backup/image_backup/%1").arg(strDate));
        CheckAndCreateDir(QString("/home/birdhead/backup/image_backup/%1/%2").arg(strDate).arg(strPatientID));

        QFileInfo fileCheck(strDest);
        if(fileCheck.exists()==false)
        {
            QFile fileBackup(strFilebackup);
            fileBackup.copy(strDest);
            fileBackup.close();
        }
    }

    pListCapture = pCommonData->GetListCaptureImage();
    {
        for(i=0 ; i<pListCapture->size() ; i++)
        {
            CAPTURE_IMAGE* pCaptureImage = (*pListCapture)[i];
            if(pCaptureImage->IsBackup()==false)
            {
                for(j=0 ; j<listBackup.size() ; j++)
                {
                    QString strFilebackup = listBackup[j];
                    if(strFilebackup==pCaptureImage->m_strImageFilename)
                    {
                        pCaptureImage->m_bBackup = true;
                    }
                }
            }
        }

    }
    pCommonData->ReleaseListCaptureImage();
}

void SThreadImageSave::USBBackup()
{
    USBBackupInner();
    usleep(100*1000);

    bool bCheckBackup = m_nCurrentState&0x400;

    if(bCheckBackup==false)
    {
        USBBackupInner();
    }
}


bool SThreadImageSave::IsExecuteBackup()
{
    return m_bExecuteUSBBackup;
}


void SThreadImageSave::SetExecuteBackup(bool bBackup)
{
    if(bBackup==true)
    {
        //MountUSBBackup();
        m_nCurrentState = (m_nCurrentState | 0x400);
    }
    else
    {
        m_nCurrentState = (m_nCurrentState & ~0x400);
        while(m_bExecuteUSBBackup==true)
        {
            usleep(100);
        }
        //UmountUSBBackup();
    }
}

void SThreadImageSave::MountUSBBackup()
{
    bool bMount = false;
    QProcess processCheckMount;
    processCheckMount.start("mount");
    while(processCheckMount.waitForStarted(100)==false)
    {
        usleep(1000);
    }
    bool retval = false;
    QByteArray buffer;

    while ((retval = processCheckMount.waitForFinished(100)))
    {
        usleep(1000);
    }
    buffer.append(processCheckMount.readAll());

    processCheckMount.terminate();
    processCheckMount.waitForFinished(100);
    processCheckMount.deleteLater();

    QString strBufferMount = buffer.toStdString().c_str();
    if(strBufferMount.contains("backup")==true)
    {
        //Already mounted
        bMount = true;
    }

    buffer.clear();

    if(bMount==true)
    {
        return;
    }

    QProcess process1;
    QProcess process2;

    process1.setStandardOutputProcess(&process2);

    process1.start("echo 1");
#ifdef _PC
    process2.start("sudo -S mount -o uid=1000,gid=1000 /dev/sdb1 /home/birdhead/backup");
#else
    process2.start("sudo -S mount -o uid=1000,gid=1000 /dev/sda1 /home/birdhead/backup");
#endif
    process2.setProcessChannelMode(QProcess::ForwardedChannels);

    // Wait for it to start
    if(!process1.waitForStarted())
        return;


    // To be fair: you only need to wait here for a bit with shutdown,
    // but I will still leave the rest here for a generic solution
    while ((retval = process2.waitForFinished()))
    {
        buffer.append(process2.readAll());
    }


    process1.terminate();
    process2.terminate();

    process1.waitForFinished(100);
    process2.waitForFinished(100);

    process1.deleteLater();
    process2.deleteLater();

    buffer.clear();
}

void SThreadImageSave::UmountUSBBackup()
{
    bool bMount = true;
    QProcess processCheckMount;
    processCheckMount.start("mount");
    while(processCheckMount.waitForStarted(100)==false)
    {
        usleep(1000);
    }
    bool retval = false;
    QByteArray buffer;

    while ((retval = processCheckMount.waitForFinished(100)))
    {
        usleep(1000);
    }
    buffer.append(processCheckMount.readAll());

    processCheckMount.terminate();
    processCheckMount.waitForFinished(100);
    processCheckMount.deleteLater();

    QString strBufferMount = buffer.toStdString().c_str();
    if(strBufferMount.contains("backup")==false)
    {
        //Already unmounted
        bMount = false;
    }

    buffer.clear();

    if(bMount==false)
    {
        return;
    }

    QProcess process1;
    QProcess process2;

    process1.setStandardOutputProcess(&process2);

    process1.start("echo 1");
#ifdef _PC
    process2.start("sudo -S umount /home/birdhead/backup");
#else
    process2.start("sudo -S umount /home/birdhead/backup");
#endif
    process2.setProcessChannelMode(QProcess::ForwardedChannels);

    // Wait for it to start
    if(!process1.waitForStarted())
        return;


    // To be fair: you only need to wait here for a bit with shutdown,
    // but I will still leave the rest here for a generic solution
    while ((retval = process2.waitForFinished()))
    {
        buffer.append(process2.readAll());
    }


    process1.terminate();
    process2.terminate();

    process1.waitForFinished(100);
    process2.waitForFinished(100);

    process1.deleteLater();
    process2.deleteLater();

    buffer.clear();
}

void SThreadImageSave::SetExecuteDetect(bool bDetect)
{
    if(bDetect==true)
    {
        m_nCurrentState = (m_nCurrentState | 0x10);
    }
    else
    {
        m_nCurrentState = (m_nCurrentState & ~0x10);
    }
}
