#include "HIKBallCamera.h"
#include "FormatTrans.h"
#include <vector>
#include <sstream>

HIKBallCamera::HIKBallCamera(){

};

struct PTZ{
    float P;
    float T;
    float Z;
};

PTZ PTZDATA;

std::vector<std::string> velocity = {"0a","14","1e","28","32","3c","ff"};

bool HIKBallCamera::InitBallCamera(std::string ip, std::string port, std::string username, std::string password, std::string BallMachineType)
{
    int res = Login(ip, port, username, password);
    if (res != 0){
        std::cout << "Incorrect Login" << std::endl;
        return false;
    }

    m_Channel = DeviceInfo.byStartChan;
    this->BallMachineType = BallMachineType;

    //建立透明通道
    NET_DVR_SERIALSTART_V40 struSerialParam = { 0 };
    struSerialParam.dwSize = sizeof(struSerialParam);
    struSerialParam.dwSerialType = 2;//1:232串口；2:485串口
    struSerialParam.bySerialNum = 1;//串口编号（设备支持多个RS232串口时有效）
    lTranHandle = NET_DVR_SerialStart_V40(LoginID, &struSerialParam, sizeof(struSerialParam), g_fSerialDataCallBack, NULL);//设置回调函数获取透传数据
    if (lTranHandle < 0)
    {
        printf("NET_DVR_SerialStart error, %d\n", NET_DVR_GetLastError());
        NET_DVR_Logout(LoginID);
        NET_DVR_Cleanup();
        return false;
    }

    return true;
}

//回调透传数据函数的外部实现
void CALLBACK HIKBallCamera::g_fSerialDataCallBack(LONG lSerialHandle,	LONG lChannel, char *pRecvDataBuffer, DWORD dwBufSize, void *pUser)
{
    std::string type = charToHex(pRecvDataBuffer[3]);
    if (type=="59"){
        PTZDATA.P = float(hexadecimalToDecimal(charToHex(pRecvDataBuffer[4])+charToHex(pRecvDataBuffer[5])))/100.0;
    }else if (type == "5B"){
        PTZDATA.T = float(hexadecimalToDecimal(charToHex(pRecvDataBuffer[4])+charToHex(pRecvDataBuffer[5])))/100.0;
    }else if (type == "5D"){
        PTZDATA.Z = float(hexadecimalToDecimal(charToHex(pRecvDataBuffer[4])+charToHex(pRecvDataBuffer[5])))/100.0;
    }
}

bool HIKBallCamera::PtzControl(int command, int stop, int speed)
{
    bool Ret = false;
    //use HIK SDK to control the ball camera
    Ret = NET_DVR_PTZControlWithSpeed_Other(LoginID,m_Channel, command, stop, speed);

    //get the error code
    if(!Ret)
    {
        std::cout << "PTZ control failed! Error code: " << NET_DVR_GetLastError() << std::endl;
        return false;
    }
    return true;
}

bool HIKBallCamera::PtzControlLeft(int speed,int state)
{
    if (BallMachineType=="BuKongQiu") {
        std::string buf = "ff 01 00 04 "+velocity[speed - 1]+" 00";
        buf = buf +" "+ verify(buf);
        SerialSend(PrepareHexString(buf));
        return true;
    }else{
        return PtzControl(PAN_LEFT, state, speed);
    }
}

bool HIKBallCamera::PtzControlRight(int speed,int state)
{
    if (BallMachineType=="BuKongQiu") {
        std::string buf = "ff 01 00 02 "+velocity[speed - 1]+" 00";
        buf = buf +" "+ verify(buf);
        SerialSend(PrepareHexString(buf));
        return true;
    }else{
        return PtzControl(PAN_RIGHT, 0, speed);
    }
}

bool HIKBallCamera::PtzControlUp(int speed,int state)
{
    if (BallMachineType=="BuKongQiu") {
        std::string buf = "ff 01 00 08 00 "+velocity[speed - 1];
        buf = buf +" "+ verify(buf);
        SerialSend(PrepareHexString(buf));
        return true;
    }else{
        return PtzControl(TILT_UP, 0, speed);
    }
}

bool HIKBallCamera::PtzControlDown(int speed,int state)
{
    if (BallMachineType=="BuKongQiu") {
        std::string buf = "ff 01 00 10 00 "+velocity[speed - 1];
        buf = buf +" "+ verify(buf);
        SerialSend(PrepareHexString(buf));
        return true;
    }else{
        return PtzControl(TILT_DOWN, 0, speed);
    }
}

bool HIKBallCamera::PtzControlZoomIn(int speed,int state)
{
    if (BallMachineType=="BuKongQiu") {
        SerialSend(PrepareHexString("ff 01 00 20 00 00 21"));
        return true;
    }else{
        return PtzControl(ZOOM_IN, 0, speed);
    }
}

bool HIKBallCamera::PtzControlZoomOut(int speed,int state)
{
    if (BallMachineType=="BuKongQiu") {
        SerialSend(PrepareHexString("ff 01 00 40 00 00 41"));
        return true;
    }else{
        return PtzControl(ZOOM_OUT, 0, speed);
    }
}


bool HIKBallCamera::PtzControlFocusAdd(int speed,int state){
    if (BallMachineType=="BuKongQiu") {
        std::cout << "ff 01 01 00 00 00 02" << std::endl;
        SerialSend(PrepareHexString("ff 01 01 00 00 00 02"));
        return true;
    }else{
        return PtzControl(ZOOM_OUT, 1, speed);
    }
}

bool HIKBallCamera::PtzControlFocusSub(int speed,int state){
    if (BallMachineType=="BuKongQiu") {
        std::cout << "ff 01 00 80 00 00 81" << std::endl;
        SerialSend(PrepareHexString("ff 01 00 80 00 00 81"));
        return true;
    }else{
        return PtzControl(ZOOM_OUT, 1, speed);
    }
}

bool HIKBallCamera::PtzControlStop(){
    SerialSend(PrepareHexString("ff 01 00 00 00 00 01"));
    return true;
}


bool HIKBallCamera::PtzControlUpLeft(int speed,int state)
{
    if (BallMachineType=="BuKongQiu") {
        std::string buf = "ff 01 00 0c "+velocity[speed - 1]+" " + velocity[speed - 1];
        buf = buf +" "+ verify(buf);
        SerialSend(PrepareHexString(buf));
        return true;
    }else{
        return PtzControl(UP_LEFT, state, speed);
    }
}

bool HIKBallCamera::PtzControlUpRight(int speed,int state)
{
    if (BallMachineType=="BuKongQiu") {
        std::string buf = "ff 01 00 0a "+velocity[speed - 1]+" " + velocity[speed - 1];
        buf = buf +" "+ verify(buf);
        SerialSend(PrepareHexString(buf));
        return true;
    }else{
        return PtzControl(UP_RIGHT, 0, speed);
    }
}

bool HIKBallCamera::PtzControlDownLeft(int speed,int state)
{
    if (BallMachineType=="BuKongQiu") {
        std::string buf = "ff 01 00 14 "+velocity[speed - 1]+" " + velocity[speed - 1];
        buf = buf +" "+ verify(buf);
        SerialSend(PrepareHexString(buf));
        return true;
    }else{
        return PtzControl(DOWN_LEFT, 0, speed);
    }
}

bool HIKBallCamera::PtzControlDownRight(int speed,int state)
{
    if (BallMachineType=="BuKongQiu") {
        std::string buf = "ff 01 00 12 "+velocity[speed - 1]+" " + velocity[speed - 1];
        buf = buf +" "+ verify(buf);
        SerialSend(PrepareHexString(buf));
        return true;
    }else{
        return PtzControl(DOWN_RIGHT, 0, speed);
    }
}

std::string addSpacesEveryTwoWords(const std::string& hex) {
    std::ostringstream result;

    int len = hex.length();
    // 如果十六进制字符串的长度是奇数，则在前面添加一个 0
    std::string paddedHex = (len % 2 == 1) ? "0" + hex : hex;
    // 遍历字符串，每两个字符分割一次
    for (size_t i = 0; i < paddedHex.length(); i += 2) {
        if (i != 0) {
            result << " ";
        }
        result << paddedHex.substr(i, 2);
    }
    return result.str();
}
std::string padding(const std::string& hex){
    if (hex.length()==2){
        return "00 "+hex;
    } else{
        return hex;
    }
}


// PTZ 跳转到指定位置
bool HIKBallCamera::PtzGotoPut(int Action, float P, float T, float Z)
{
    if (BallMachineType=="BuKongQiu"){
        std::string pHex = decimalToHexadecimal(P * 100);
        pHex = padding(addSpacesEveryTwoWords(pHex));
        std::string tHex = decimalToHexadecimal(T * 100);
        tHex = padding(addSpacesEveryTwoWords(tHex));
        std::string zHex = decimalToHexadecimal(Z * 100);
        zHex = padding(addSpacesEveryTwoWords(zHex));
        std::string pBuf = "ff 01 00 4b "+ pHex;
        std::string tBuf = "ff 01 00 4d "+ tHex;
        std::string zBuf = "ff 01 00 4f "+ zHex;
        pBuf = pBuf+" "+verify(pBuf);
        tBuf = tBuf+" "+verify(tBuf);
        zBuf = zBuf+" "+verify(zBuf);
        switch (Action) {
            case 1:
                SerialSend(PrepareHexString(pBuf)); // 设置 P
                SerialSend(PrepareHexString(tBuf)); // 设置 T
                SerialSend(PrepareHexString(zBuf)); // 设置 Z
                break;
            case 2:
                SerialSend(PrepareHexString(pBuf)); // 设置 P
                break;
            case 3:
                SerialSend(PrepareHexString(tBuf)); // 设置 T
                break;
            case 4:
                SerialSend(PrepareHexString(zBuf)); // 设置 Z
                break;
            case 5:
                SerialSend(PrepareHexString(pBuf)); // 设置 P
                SerialSend(PrepareHexString(tBuf)); // 设置 T
                break;
            default:
                break;
        }
        return true;
    }else{
        NET_DVR_PTZPOS ptzPosCurrent;
        ptzPosCurrent.wPanPos = DEC2HEX(P);
        ptzPosCurrent.wTiltPos = DEC2HEX(T);
        ptzPosCurrent.wAction = 5;

        bool b = NET_DVR_SetDVRConfig(LoginID, NET_DVR_SET_PTZPOS, m_Channel, &ptzPosCurrent, sizeof(NET_DVR_PTZPOS));
        return b;
    }
}
bool HIKBallCamera::SerialSend(const std::string& hex){
    char m_DataBuf[50];
    int m_DataLen;
    int len = hex.length();
    m_DataLen = len<1024 ? len : 1024;
    memcpy(m_DataBuf,hex.c_str(),m_DataLen);
    return NET_DVR_SerialSend(lTranHandle,1, m_DataBuf, m_DataLen);
}

bool HIKBallCamera::PtzGet(float* posP, float* posT, float* posZ) {
    if (BallMachineType=="BuKongQiu"){
        SerialSend(PrepareHexString("ff 01 00 51 00 00 52"));
        SerialSend(PrepareHexString("ff 01 00 53 00 00 54"));
        SerialSend(PrepareHexString("ff 01 00 55 00 00 56"));
        SLEEP(1);
        *posP = PTZDATA.P;
        *posT = PTZDATA.T;
        *posZ = PTZDATA.Z;
        return true;
    }else{
        NET_DVR_PTZPOS ptzPosCurrent;
        DWORD dwtmp;
        bool b = NET_DVR_GetDVRConfig(LoginID, NET_DVR_GET_PTZPOS, m_Channel, &ptzPosCurrent, sizeof(NET_DVR_PTZPOS),&dwtmp);
        float P = HEX2DEC(ptzPosCurrent.wPanPos);
        float T = HEX2DEC(ptzPosCurrent.wTiltPos);
        float Z = HEX2DEC(ptzPosCurrent.wZoomPos);
        posP = &P;
        posT = &T;
        posZ = &Z;
        return b;
    }
}

bool HIKBallCamera::CmdSwitch(int direction,int speed,int state){
    bool Res = false;
    switch (direction) {
        case PTZ_LEFT:
            Res = PtzControlLeft(speed,state);
            break;
        case PTZ_RIGHT:
            Res = PtzControlRight(speed,state);
            break;
        case PTZ_UP:
            Res = PtzControlUp(speed,state);
            break;
        case PTZ_DOWN:
            Res = PtzControlDown(speed,state);
            break;
        case PTZ_UP_LEFT:
            Res = PtzControlUpLeft(speed,state);
            break;
        case PTZ_UP_RIGHT:
            Res = PtzControlUpRight(speed,state);
            break;
        case PTZ_DOWN_LEFT:
            Res = PtzControlDownLeft(speed,state);
            break;
        case PTZ_DOWN_RIGHT:
            Res = PtzControlDownRight(speed,state);
            break;
        case PTZ_ZOOM_IN:
            Res = PtzControlZoomIn(speed,state);
            break;
        case PTZ_ZOOM_OUT:
            Res = PtzControlZoomOut(speed,state);
            break;
        case PTZ_Focus_Far:
            Res = PtzControlFocusSub(speed,state);
            break;
        case PTZ_Focus_Near:
            Res = PtzControlFocusAdd(speed,state);
            break;
    }
    return Res;
}

bool HIKBallCamera::StopBus(int direction) {
    if (BallMachineType=="BuKongQiu"){
        return PtzControlStop();
    }
    return CmdSwitch(direction,0,1);
}

bool HIKBallCamera::StartBus(int direction, int speed) {
    return CmdSwitch(direction,speed,0);
}
