package Yoseen;

import sun.misc.Unsafe;

public class HKNETDevice {
    Unsafe _unsafe;
    long _hknet;
    long _mem;

    public HKNETDevice() {
        _unsafe = LibHK.LibHKclass.__unsafe;
        _hknet = 0;
        _mem = 0;
    }

    public int init() {
        if (0 != _hknet) return 0;
        _hknet = LibHK.Instance.hkCreate();
        _mem = _unsafe.allocateMemory(1024 * 1024);
        return 0;
    }

    public void free() {
        if (0 == _hknet) return;

        _unsafe.putLong(_mem, _hknet);
        LibHK.Instance.hkFree(_mem);
        _unsafe.freeMemory(_mem);
        _hknet = 0;
        _mem = 0;
    }

    public int login(String ip, String username, String password) {
        if (0 == _hknet) return EError.EError_InvalidState;

        int ret;
        ret = LibHK.Instance.hkLogin(_hknet, ip, username, password);
        return ret;
    }

    public int logout() {
        if (0 == _hknet) return EError.EError_InvalidState;

        int ret;
        ret = LibHK.Instance.hkLogout(_hknet);
        return ret;
    }

    public int ptzControl(int act, int arg) {
        if (0 == _hknet) return EError.EError_InvalidState;

        int ret;
        ret = LibHK.Instance.hkPtzControl(_hknet, act, arg);
        return ret;
    }

    public int ptzControl_Stop(int act, int arg) {
        if (0 == _hknet) return EError.EError_InvalidState;

        int ret;
        ret = LibHK.Instance.hkPtzControl_Stop(_hknet, act, arg);
        return ret;
    }

    public int ptzControl_GetPtz(int[] ptz, int timeout) {
        if (0 == _hknet) return EError.EError_InvalidState;

        int ret;

        //
        long addr_pan = _mem;
        long addr_tilt = _mem + 4;
        long addr_zoom = _mem + 8;
        ret = LibHK.Instance.hkPtzControl_GetPtz(_hknet, addr_pan, addr_tilt, addr_zoom, timeout);
        if (0 == ret) {
            ptz[0] = _unsafe.getInt(addr_pan);
            ptz[1] = _unsafe.getInt(addr_tilt);
            ptz[2] = _unsafe.getInt(addr_zoom);
        }
        return ret;
    }

    public int ptzControl_SetPtz(int[] ptz, int speed) {
        if (0 == _hknet) return EError.EError_InvalidState;

        int ret;
        ret = LibHK.Instance.hkPtzControl_SetPtz(_hknet, ptz[0], ptz[1], ptz[2]);
        return ret;
    }

    public int enableXPtz(int enable) {
        if (0 == _hknet) return EError.EError_InvalidState;
        int ret;
        if (0 == enable) {
            ret = LibHK.Instance.hkSerialStop(_hknet);
        } else {
            ret = LibHK.Instance.hkSerialStart(_hknet, 0, 0);
        }
        return ret;
    }

}
