#include "generic_vidicon.h"
#include "HCNetSDK.h"
#include "common/snowflake.h"
#include "common/sys_util.h"

namespace zsy
{
    GenericVidicon::~GenericVidicon()
    {
    }

    GenericVidicon::GenericVidicon(const VidiconProperties &config)
        : config(config)
    {
        SysUtil::createDirs(SysUtil::HOME_DIR + "\\temp");
    }

    std::string GenericVidicon::photograph()
    {
        try
        {
            LOGGER_INFO("摄像机正在拍照，设备名称：{}", config.name);

            BOOL succ = NET_DVR_Init();
            if (!succ)
            {
                LOGGER_ERROR("摄像机初始化失败：{} {}", NET_DVR_GetLastError(), NET_DVR_GetErrorMsg());
                NET_DVR_Cleanup();
                return {};
            }
            auto logPath = SysUtil::ch_vlt((SysUtil::HOME_DIR + "\\logs").c_str());
            succ = NET_DVR_SetLogToFile(3, logPath.get(), true);
            if (!succ)
            {
                LOGGER_ERROR("摄像机日志设置失败：{} {}", NET_DVR_GetLastError(), NET_DVR_GetErrorMsg());
                NET_DVR_Cleanup();
                return {};
            }
            NET_DVR_DEVICEINFO_V30 DeviceInfoTmp{};

            auto ip = SysUtil::ch_vlt(config.ip.c_str());
            auto username = SysUtil::ch_vlt(config.username.c_str());
            auto passwd = SysUtil::ch_vlt(config.passwd.c_str());
            LONG lLoginID = NET_DVR_Login_V30(ip.get(),
                                              config.port,
                                              username.get(),
                                              passwd.get(), &DeviceInfoTmp);

            if (lLoginID == -1)
            {
                DWORD e = NET_DVR_GetLastError();
                auto m = NET_DVR_GetErrorMsg();
                LOGGER_ERROR("摄像机登录失败：{} {}", e, m);
                NET_DVR_Cleanup();
                return {};
            }

            NET_DVR_JPEGPARA JpgPara{};
            JpgPara.wPicSize = 0xff;
            JpgPara.wPicQuality = 0;
            const auto filename = "car_body_" + Snowflake::genIdStr() + ".jpg";
            std::string path = SysUtil::HOME_DIR + "\\temp\\" + filename;
            const auto path_ = SysUtil::ch_vlt(path.c_str());
            auto filePath = path_.get();
            if (!NET_DVR_CaptureJPEGPicture(lLoginID, 1, &JpgPara, filePath))
            {
                LOGGER_ERROR("摄像机拍照失败：{} {}", NET_DVR_GetLastError(), NET_DVR_GetErrorMsg());
                NET_DVR_Cleanup();
                return {};
            }
            LOGGER_INFO("摄像机拍照完成：{}", path);

            NET_DVR_Logout_V30(lLoginID);
            NET_DVR_Cleanup();

            return path;
        } catch (std::exception &e)
        {
            LOGGER_ERROR("摄像机拍照失败：{}", e.what());
            return {};
        }
        catch (...)
        {
            LOGGER_ERROR("未知异常，摄像机拍照失败");
            return {};
        }
    }
} // zsy
