#include "ReadImgEngine.h"
#include <algorithm>
#include <string>
#include <regex>
#include <boost/filesystem.hpp>
#include <sys/stat.h>
#include "myutils.h"

using namespace ai_matrix;

namespace
{
    //按照文件名排序
    bool CompareFileName(const std::string &sParam1, const std::string &sParam2)
    {
        int iPos1 = sParam1.find(".");
        int iPos11 = sParam1.find_last_of("/");
        int iPos2 = sParam2.find(".");
        int iPos22 = sParam2.find_last_of("/");
        std::string sFileName1 = sParam1.substr(iPos11+1, iPos1-iPos11-1);
        std::string sFileName2 = sParam2.substr(iPos22+1, iPos2-iPos22-1);
        return (atoi(sFileName1.c_str()) < atoi(sFileName2.c_str()));
    }
}

ReadImgEngine::ReadImgEngine() {}

ReadImgEngine::~ReadImgEngine() {}

APP_ERROR ReadImgEngine::Init()
{
    bUseEngine_ = true;
    dataSourceConfig_ = MyYaml::GetIns()->GetDataSourceConfigById(engineId_); //获取摄像机参数
    if (MyYaml::GetIns()->GetStringValue("gc_data_source") != "images" || !dataSourceConfig_.bUse)
    {
        bUseEngine_ = false;
        LogWarn << "engineId_:" << engineId_ << " not use engine";
        return APP_ERR_OK;
    }

    strPort0_ = engineName_ + "_" + std::to_string(engineId_) + "_0";
    LogInfo << "engineId_:" << engineId_ << " ReadImgEngine Init ok";
    return APP_ERR_OK;
}

APP_ERROR ReadImgEngine::DeInit()
{
    if (!bUseEngine_)
    {
        LogWarn << "engineId_:" << engineId_ << " not use engine";
        return APP_ERR_OK;
    }

    LogInfo << "engineId_:" << engineId_ << " ReadImgEngine DeInit ok";
    return APP_ERR_OK;
}

void ReadImgEngine::RecursionReadDir(const std::string &strDir)
{
    boost::filesystem::directory_iterator end_itr;
    for (boost::filesystem::directory_iterator itr(strDir); itr != end_itr; ++itr)
    {
        if (boost::filesystem::is_directory(*itr)) //文件夹
        {
            RecursionReadDir(itr->path().string());
        }
        else
        {
            std::string strExt = itr->path().extension().string();
            if (strExt.compare(".jpg") == 0)
            {
                vecFiles_.push_back(itr->path().string()); //保存绝对路径
            }
        }
    }
}

std::string ReadImgEngine::GetFileName(const std::string &strParam)
{
    int iPos = strParam.find(".");
    int iPos1 = strParam.find_last_of("/");
    return strParam.substr(iPos1 + 1, iPos - iPos1 - 1);
}

APP_ERROR ReadImgEngine::Process()
{

    if (!bUseEngine_)
    {
        LogWarn << "engineId_:" << engineId_ << " not use engine";
        return APP_ERR_OK;
    }

    int iRet = APP_ERR_OK;
    RecursionReadDir(dataSourceConfig_.strUrl); //递归读取文件夹
    if (vecFiles_.size() == 0)
    {
        LogError << "engineId_:" << engineId_ << " no  file";
        return APP_ERR_COMM_FAILURE;
    }
    std::sort(vecFiles_.begin(), vecFiles_.end(), CompareFileName);
    LogInfo << "engineId_:" << engineId_ << " vecFiles_ size: " << vecFiles_.size();

    int iFileIndex = 0; //文件序号
    while (!isStop_)
    {

        std::string strFilePath = vecFiles_.at(iFileIndex);
        cv::Mat matBGR = cv::imread(strFilePath);
        
        //组织数据
        std::shared_ptr<ProcessData> pProcessData = std::make_shared<ProcessData>();
        pProcessData->iWidth = matBGR.cols;
        pProcessData->iHeight = matBGR.rows;
        pProcessData->iRate = 25;
        pProcessData->i64TimeStamp = MyUtils::getins()->GetCurrentTimeMillis();
        pProcessData->iDataSource = engineId_;

        uint32_t iBGRSize = pProcessData->iWidth * pProcessData->iHeight * 3;
        void *pBGRBuffer = nullptr;
        pBGRBuffer = new uint8_t[iBGRSize];
        memcpy(pBGRBuffer, matBGR.data, iBGRSize);
        pProcessData->pData.reset(pBGRBuffer, [](void *data){if(data) {delete[] data; data = nullptr;} }); // 智能指针管理内存
        pProcessData->iSize = iBGRSize;

        // //读取文件内容
        // RawData rawData;
        // iRet = ReadFile(strFilePath, rawData);
        // if (iRet != APP_ERR_OK)
        // {
        //     LogError << "engineId_:" << engineId_ << " Failed to read image on " << strFilePath << ", iRet = " << iRet << ".";
        //     return iRet;
        // }

        // //组织数据
        // std::shared_ptr<FrameData> pFrameData = std::make_shared<FrameData>();
        // pFrameData->iDataSource = engineId_;
        // pFrameData->iFrameId = iFileIndex + 1;
        // pFrameData->iSize = rawData.lenOfByte;
        // pFrameData->pData = rawData.data;
        // pFrameData->i64TimeStamp = MyUtils::getins()->GetCurrentTimeMillis();
        iRet = outputQueMap_[strPort0_]->push(std::static_pointer_cast<void>(pProcessData));

        iFileIndex = (iFileIndex + 1) % vecFiles_.size();
        if (iFileIndex == 0)
        {
            LogInfo << "engineId_:" << engineId_ << " read images finish ";
            while (!isStop_)
            {
                usleep(100000); //100ms
            }

            //break; //只发布一遍
        }
        //模拟1秒25帧
        usleep(40000); //40ms
    }
    return APP_ERR_OK;
}

