#include "multi_ipnc_demo.h"
#include "nss_common.h"

#include <QtGui/QApplication>
#include <QtCore/QtCore>
#include <QtGui/QDesktopServices>
#include <QtGui/QMessageBox>

#include "q_fader_widget.h"

const int kShutterValues[] = {
    25,50,60,80,100,120,125,150,180,200,250,500,1000,2000,4000,10000
} ;
const int kShutterValuesCount = sizeof(kShutterValues) / sizeof(int);

const char kIrisValues[][5] = {
    "f1.6","f2.0","f2.4","f2.8","f3.4","f4.0","f4.8","f5.6","f6.8","f9.6","f11","f14","f16","f19","f22"
} ;

QString formatMBytesStr( unsigned __int64 mbytes )
{
    char szBuf[MAX_PATH];
    ZeroMemory( szBuf, sizeof(char)*MAX_PATH );

    if (mbytes < 1024) {
        _snprintf_s( szBuf, _countof(szBuf), MAX_PATH - 1, "%d MB", mbytes );
    }
    else {
        float uPercent = mbytes / (float)1024;
        _snprintf_s( szBuf, _countof(szBuf), MAX_PATH - 1, "%.2f GB", uPercent );
    }
    return szBuf;
}

QString sd_status_str(int status)
{
    switch (status)
    {
    case 0:
    	return "not exist";
    case 1:
        return "not format";
    case 2:
        return "formatting";
    case 3:
        return "unmounted";
    case 4:
        return "mounted";
    case 5:
        return "ready";
    default:
        return "unknown";
    }
}
#define DAY_SECONDS (60*60*24)

#define setbit(x,y) x|=(1<<y)
#define clrbit(x,y) x&=~(1<<y)
#define getbit(x,pos) ((x) >> (pos)&1)

#define UNSIGNAL_SET_CURRENT_INDEX(x,val) \
    {\
        x->blockSignals(true);\
        x->setCurrentIndex(val);\
        x->blockSignals(false);\
    }

#define UNSIGNAL_SET_VALUE(x,val) \
    {\
        x->blockSignals(true);\
        x->setValue(val);\
        x->blockSignals(false);\
    }

#define QT_CHECK_STATE(x) (x ? Qt::Checked : Qt::Unchecked)
#define QT_CHECK_STATE2BOOL(x) (x == Qt::Unchecked ? 0 : 1)
#define QT_CHECK_STATE2BOOL_EX(x) ui.##x##->checkState() == Qt::Unchecked ? 0 : 1
const int kIrisValuesCount = sizeof(kIrisValues) / 5;

multi_ipnc_demo* multi_ipnc_demo::instance_ = NULL;

multi_ipnc_demo::multi_ipnc_demo(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags),
      sel_channel_(0),
      sel_stream_(0),
      menu_device_(NULL),
      menu_channel_(NULL),
      grid_show_full_(false),
      client_show_full_(false),
      ui_modify_device_(NULL),
      ptz_auto_(false),
      ddnslist_(NULL)
{
    ui.setupUi(this);
    showMaximized();
    InitObject();

    memset(&alarm_schedule_,0,sizeof(NsstAlarmSchedule)*NS_ALARM_TYPE_COUNT);
    for (unsigned i = 0;i < NS_ALARM_TYPE_COUNT;++i)
    {
        alarm_schedule_[i].alarm_type = (NS_ALARM_TYPE)i;
    }
}

multi_ipnc_demo::~multi_ipnc_demo()
{
    delete qdbg_;
    qdbg_ = NULL;
}

void multi_ipnc_demo::InitObject()
{
    ui.tedtLog->setOpenLinks(false);  
    connect(ui.tedtLog,SIGNAL(anchorClicked(const QUrl &)),this,SLOT(OnClickUrl(const QUrl &)));
    AppSettingsInstance()->GetDeviceInfo(&device_info_);
    //////////////////////////////////////////////////////////////////////////
    motion_trigger_output_.push_back(ui.cbMotionTriggerO1);
    motion_trigger_output_.push_back(ui.cbMotionTriggerO2);
    motion_trigger_output_.push_back(ui.cbMotionTriggerO3);
    motion_trigger_output_.push_back(ui.cbMotionTriggerO4);
    motion_trigger_output_.push_back(ui.cbMotionTriggerO5);
    motion_trigger_output_.push_back(ui.cbMotionTriggerO6);
    motion_trigger_output_.push_back(ui.cbMotionTriggerO7);
    motion_trigger_output_.push_back(ui.cbMotionTriggerO8);

    exp_trigger_output_.push_back(ui.cbExpTriggerO1);
    exp_trigger_output_.push_back(ui.cbExpTriggerO2);
    exp_trigger_output_.push_back(ui.cbExpTriggerO3);
    exp_trigger_output_.push_back(ui.cbExpTriggerO4);
    exp_trigger_output_.push_back(ui.cbExpTriggerO5);
    exp_trigger_output_.push_back(ui.cbExpTriggerO6);
    exp_trigger_output_.push_back(ui.cbExpTriggerO7);
    exp_trigger_output_.push_back(ui.cbExpTriggerO8);

    portin_trigger_output_.push_back(ui.cbPortInTriggerO1);
    portin_trigger_output_.push_back(ui.cbPortInTriggerO2);
    portin_trigger_output_.push_back(ui.cbPortInTriggerO3);
    portin_trigger_output_.push_back(ui.cbPortInTriggerO4);
    portin_trigger_output_.push_back(ui.cbPortInTriggerO5);
    portin_trigger_output_.push_back(ui.cbPortInTriggerO6);
    portin_trigger_output_.push_back(ui.cbPortInTriggerO7);
    portin_trigger_output_.push_back(ui.cbPortInTriggerO8);
    
    //////////////////////////////////////////////////////////////////////////
    schedule_start_.push_back(ui.teSection11);
    schedule_start_.push_back(ui.teSection21);
    schedule_start_.push_back(ui.teSection31);
    schedule_start_.push_back(ui.teSection41);
    schedule_start_.push_back(ui.teSection51);
    schedule_start_.push_back(ui.teSection61);
    schedule_start_.push_back(ui.teSection71);
    schedule_start_.push_back(ui.teSection81);

    schedule_end_.push_back(ui.teSection12);
    schedule_end_.push_back(ui.teSection22);
    schedule_end_.push_back(ui.teSection32);
    schedule_end_.push_back(ui.teSection42);
    schedule_end_.push_back(ui.teSection52);
    schedule_end_.push_back(ui.teSection62);
    schedule_end_.push_back(ui.teSection72);
    schedule_end_.push_back(ui.teSection82);

    schedule_copy_.push_back(ui.cbSchDay1);
    schedule_copy_.push_back(ui.cbSchDay2);
    schedule_copy_.push_back(ui.cbSchDay3);
    schedule_copy_.push_back(ui.cbSchDay4);
    schedule_copy_.push_back(ui.cbSchDay5);
    schedule_copy_.push_back(ui.cbSchDay6);
    schedule_copy_.push_back(ui.cbSchDay0);
    ////////record//////////////////////////////////////////////////////////////////
    rec_schedule_start_.push_back(ui.teSection11_2);
    rec_schedule_start_.push_back(ui.teSection21_2);
    rec_schedule_start_.push_back(ui.teSection31_2);
    rec_schedule_start_.push_back(ui.teSection41_2);
    rec_schedule_start_.push_back(ui.teSection51_2);
    rec_schedule_start_.push_back(ui.teSection61_2);
    rec_schedule_start_.push_back(ui.teSection71_2);
    rec_schedule_start_.push_back(ui.teSection81_2);

    rec_schedule_end_.push_back(ui.teSection12_2);
    rec_schedule_end_.push_back(ui.teSection22_2);
    rec_schedule_end_.push_back(ui.teSection32_2);
    rec_schedule_end_.push_back(ui.teSection42_2);
    rec_schedule_end_.push_back(ui.teSection52_2);
    rec_schedule_end_.push_back(ui.teSection62_2);
    rec_schedule_end_.push_back(ui.teSection72_2);
    rec_schedule_end_.push_back(ui.teSection82_2);

    rec_schedule_copy_.push_back(ui.cbSchDay1_2);
    rec_schedule_copy_.push_back(ui.cbSchDay2_2);
    rec_schedule_copy_.push_back(ui.cbSchDay3_2);
    rec_schedule_copy_.push_back(ui.cbSchDay4_2);
    rec_schedule_copy_.push_back(ui.cbSchDay5_2);
    rec_schedule_copy_.push_back(ui.cbSchDay6_2);
    rec_schedule_copy_.push_back(ui.cbSchDay0_2);

    rec_type_group_.push_back(ui.cbbRTypeSec1);
    rec_type_group_.push_back(ui.cbbRTypeSec2);
    rec_type_group_.push_back(ui.cbbRTypeSec3);
    rec_type_group_.push_back(ui.cbbRTypeSec4);
    rec_type_group_.push_back(ui.cbbRTypeSec5);
    rec_type_group_.push_back(ui.cbbRTypeSec6);
    rec_type_group_.push_back(ui.cbbRTypeSec7);
    rec_type_group_.push_back(ui.cbbRTypeSec8);

    for (unsigned i = 0;i < rec_type_group_.size();++i)
    {
        rec_type_group_.at(i)->addItem("Schedule");
        rec_type_group_.at(i)->addItem("Motion");
        rec_type_group_.at(i)->addItem("Alarm");
        rec_type_group_.at(i)->addItem("M or A");
        rec_type_group_.at(i)->addItem("M and A");
    }

    QObject::connect(ui.spinCaptureQuota,SIGNAL(valueChanged(int)),this,SLOT(SlotOnCaptureQuotaChanged(int)));
    //////////tree////////////////////////////////////////////////////////////////
    standard_model_ = new QStandardItemModel ;

    first_item_ = new QStandardItem(device_info_.device_ip);
    standard_model_->setItem(0,0,first_item_);
    first_item_->appendRow(new QStandardItem("channel0-main"));
    first_item_->appendRow(new QStandardItem("channel0-sub"));
    first_item_->appendRow(new QStandardItem("channel1-main"));
    first_item_->appendRow(new QStandardItem("channel1-sub"));

    ui.treev_ipnc->setModel(standard_model_);
    ui.treev_ipnc->expandAll();
    ui.treev_ipnc->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui.treev_ipnc->setContextMenuPolicy(Qt::CustomContextMenu);

    menu_device_ = new QMenu;
    menu_device_->addAction("Login",this,SLOT(DoLogin()));
    menu_device_->addAction("Logout",this,SLOT(DoLogout()));
    menu_device_->addAction("Talk On",this,SLOT(DoStartTalk()));
    menu_device_->addAction("Talk Off",this,SLOT(DoStopTalk()));
    menu_device_->addAction("Modify",this,SLOT(SlotShowModifyDeviceInfo()));

    menu_channel_ = new QMenu;
    menu_channel_->addAction("Connect",this,SLOT(DoConnect()));
    menu_channel_->addAction("Disconnect",this,SLOT(DoDisconnect()));
    menu_channel_->addAction("Connect All",this,SLOT(DoConnectAll()));
    menu_channel_->addAction("Disconnect All",this,SLOT(DoDisconnectAll()));
    menu_channel_->addAction("Open Audio",this,SLOT(DoOpenAudio()));
    menu_channel_->addAction("Close Audio",this,SLOT(DoCloseAudio()));
    menu_channel_->addAction("Show Fps",this,SLOT(OnShowFPSClick()));
    menu_channel_->addAction("Close Fps",this,SLOT(OnCloseFPSClick()));

    menu_channel_->addAction("Test Media",this,SLOT(OnTestMediaClick()));
    menu_channel_->addAction("Stop Test",this,SLOT(OnStopTestMediaClick()));

    QObject::connect(ui.treev_ipnc,SIGNAL(customContextMenuRequested(const QPoint &)),this,SLOT(OnTreeContextMenuRequested(const QPoint &))); 
    QObject::connect(ui.treev_ipnc,SIGNAL(doubleClicked(const QModelIndex)),this,SLOT(OnlineTreeViewDoubleClick(const QModelIndex))); 
    QObject::connect(ui.treev_ipnc,SIGNAL(clicked(const QModelIndex)),this,SLOT(OnlineTreeViewClick(const QModelIndex))); 
    
    ///////////panel///////////////////////////////////////////////////////////////
    for (unsigned i = 0;i < MAX_CHANNEL;++i)
    {
        for (unsigned j = 0;j < MAX_STREAM_PER_CHANNEL;++j)
        {
            QString str_name;
            str_name.sprintf("VideoForm_%d%d",i,j);
            NsstChannel nsst_channel;
            nsst_channel.dev_id = -1;
            nsst_channel.channel = i;
            nsst_channel.stream = j;
            video_widget_[i][j] = new QVideoWidget(ui.groupBox,nsst_channel);
            video_widget_[i][j]->setObjectName(str_name);
            video_widget_[i][j]->video_panel_label_->SetDelegate(this);

            ui.gridLayout->addWidget(video_widget_[i][j], i, j, 1, 1);
            //ui.groupBox->setLayout(ui.gridLayout);
            QObject::connect(video_widget_[i][j],SIGNAL(keypress(int)),this,SLOT(SlotOnVideoKeyPress(int)));
            QObject::connect(video_widget_[i][j],SIGNAL(wheel(int,int)),this,SLOT(SlotOnVideoPanelWheel(int,int)));
        }
    }
    //////////toolbar////////////////////////////////////////////////////////////////
    QToolButton *btn_fullscreen = new QToolButton;
    btn_fullscreen->setIcon(QIcon(":/multi_ipnc_demo/Resources/btn_fullscreen_normal.png"));
    btn_fullscreen->setToolTip("Full Screen");
    ui.toolbarTop->addWidget(btn_fullscreen);
    QObject::connect(btn_fullscreen,SIGNAL(clicked()),this,SLOT(OnFullScreenClick()));

    QToolButton *btn_video_statusbar = new QToolButton;
    btn_video_statusbar->setIcon(QIcon(":/multi_ipnc_demo/Resources/btn_showhide_status.png"));
    btn_video_statusbar->setToolTip("Show/Hide Status Bar");
    ui.toolbarTop->addWidget(btn_video_statusbar);
    QObject::connect(btn_video_statusbar,SIGNAL(clicked()),this,SLOT(OnVideoStatusShowHideClick()));

    QToolButton *btn_debugview = new QToolButton;
    btn_debugview->setIcon(QIcon(":/multi_ipnc_demo/Resources/btn_bug.png"));
    btn_debugview->setToolTip("Show Debug View");
    ui.toolbarTop->addWidget(btn_debugview);
    QObject::connect(btn_debugview,SIGNAL(clicked()),this,SLOT(OnDebugViewClick()));

    QToolButton *btn_playback = new QToolButton;
    btn_playback->setIcon(QIcon(":/multi_ipnc_demo/Resources/btn_open_playback.png"));
    btn_playback->setToolTip("Show Remote Playback");
    ui.toolbarTop->addWidget(btn_playback);
    QObject::connect(btn_playback,SIGNAL(clicked()),this,SLOT(OnPlaybackClick()));

    QToolButton *btn_upgrade = new QToolButton;
    btn_upgrade->setIcon(QIcon(":/multi_ipnc_demo/Resources/btn_upgrade.png"));
    btn_upgrade->setToolTip("Upgrade");
    ui.toolbarTop->addWidget(btn_upgrade);
    QObject::connect(btn_upgrade,SIGNAL(clicked()),this,SLOT(OnUpgradeClick()));
    //////////////////////////////////////////////////////////////////////////
    for (unsigned i = 0;i<kShutterValuesCount;++i)
    {
        ui.cbShutterLimit->addItem(QString("1/").append(QString::number(kShutterValues[i])),QVariant(kShutterValues[i]));
        ui.cbShutterTimes->addItem(QString("1/").append(QString::number(kShutterValues[i])),QVariant(kShutterValues[i]));
    }
    for (unsigned i = 0;i<kIrisValuesCount;++i)
    {
        ui.cbIris->addItem(QString::fromAscii(kIrisValues[i]));
    }

    //////////ptz////////////////////////////////////////////////////////////////
    QObject::connect(ui.btn_ptz_up,SIGNAL(pressed()),this,SLOT(OnPTZUpPress()));
    QObject::connect(ui.btn_ptz_up,SIGNAL(released()),this,SLOT(DoPTZStop()));
    QObject::connect(ui.btn_ptz_down,SIGNAL(pressed()),this,SLOT(OnPTZDownPress()));
    QObject::connect(ui.btn_ptz_down,SIGNAL(released()),this,SLOT(DoPTZStop()));
    QObject::connect(ui.btn_ptz_left,SIGNAL(pressed()),this,SLOT(OnPTZLeftPress()));
    QObject::connect(ui.btn_ptz_left,SIGNAL(released()),this,SLOT(DoPTZStop()));
    QObject::connect(ui.btn_ptz_right,SIGNAL(pressed()),this,SLOT(OnPTZRightPress()));
    QObject::connect(ui.btn_ptz_right,SIGNAL(released()),this,SLOT(DoPTZStop()));
    QObject::connect(ui.btn_ptz_left_top,SIGNAL(pressed()),this,SLOT(OnPTZLeftTopPress()));
    QObject::connect(ui.btn_ptz_left_top,SIGNAL(released()),this,SLOT(DoPTZStop()));
    QObject::connect(ui.btn_ptz_left_down,SIGNAL(pressed()),this,SLOT(OnPTZLeftDownPress()));
    QObject::connect(ui.btn_ptz_left_down,SIGNAL(released()),this,SLOT(DoPTZStop()));
    QObject::connect(ui.btn_ptz_right_top,SIGNAL(pressed()),this,SLOT(OnPTZRightTopPress()));
    QObject::connect(ui.btn_ptz_right_top,SIGNAL(released()),this,SLOT(DoPTZStop()));
    QObject::connect(ui.btn_ptz_right_down,SIGNAL(pressed()),this,SLOT(OnPTZRightDownPress()));
    QObject::connect(ui.btn_ptz_right_down,SIGNAL(released()),this,SLOT(DoPTZStop()));

    QObject::connect(ui.btnIrisOn,SIGNAL(pressed()),this,SLOT(OnPTZIrisOnPress()));
    QObject::connect(ui.btnIrisOff,SIGNAL(pressed()),this,SLOT(OnPTZIrisOffPress()));
    QObject::connect(ui.btnWiperOn,SIGNAL(pressed()),this,SLOT(OnPTZWiperOnPress()));
    QObject::connect(ui.btnWiperOff,SIGNAL(pressed()),this,SLOT(OnPTZWiperOffPress()));
    QObject::connect(ui.btnLightOn,SIGNAL(pressed()),this,SLOT(OnPTZLightOnPress()));
    QObject::connect(ui.btnLightOff,SIGNAL(pressed()),this,SLOT(OnPTZLightOffPress()));

    QObject::connect(ui.btn_ptz_auto,SIGNAL(clicked()),this,SLOT(OnPTZAutoClick()));
    
    for (unsigned i = 1;i <= 255;++i)
    {
        QString str;
        str.sprintf("%d",i);
        ui.cbbPreset->addItem(str);
    }

    QObject::connect(ui.btnCallPreset, SIGNAL(clicked()), this, SLOT(SlotOnCallPreset()));
    QObject::connect(ui.btnAddPreset, SIGNAL(clicked()), this, SLOT(SlotOnAddPreset()));
    QObject::connect(ui.btnDeletePreset, SIGNAL(clicked()), this, SLOT(SlotOnDeletePreset()));
    QObject::connect(ui.btnGetCameraParams,SIGNAL(clicked()),this,SLOT(SlotOnGetCameraParams()));
    QObject::connect(ui.btnSetCameraParams,SIGNAL(clicked()),this,SLOT(SetCameraParams()));

    QObject::connect(ui.btnZoomBig,SIGNAL(pressed()),this,SLOT(SlotOnZoomBig()));
    QObject::connect(ui.btnZoomBig,SIGNAL(released()),this,SLOT(DoPTZStop()));
    QObject::connect(ui.btnZoomSmall,SIGNAL(pressed()),this,SLOT(SlotOnZoomSmall()));
    QObject::connect(ui.btnZoomSmall,SIGNAL(released()),this,SLOT(DoPTZStop()));
    QObject::connect(ui.btnFocusNear,SIGNAL(pressed()),this,SLOT(SlotOnFocusNear()));
    QObject::connect(ui.btnFocusNear,SIGNAL(released()),this,SLOT(DoPTZStop()));
    QObject::connect(ui.btnFocusFar,SIGNAL(pressed()),this,SLOT(SlotOnFocusFar()));
    QObject::connect(ui.btnFocusFar,SIGNAL(released()),this,SLOT(DoPTZStop()));

    QObject::connect(ui.hsldXSpeed,SIGNAL(valueChanged(int)),this,SLOT(SlotOnSliderSpeedChanged(int)));

    QObject::connect(ui.btnGetNetConfig,SIGNAL(clicked()),this,SLOT(SlotOnGetNetConfig()));
    QObject::connect(ui.btnSetNetConfig,SIGNAL(clicked()),this,SLOT(SlotOnSetNetConfig()));

    QObject::connect(ui.btnSetMac,SIGNAL(clicked()),this,SLOT(SlotOnSetMac()));
    QObject::connect(ui.btnGetMac,SIGNAL(clicked()),this,SLOT(SlotOnGetMac()));

    QObject::connect(ui.hsldBrightness,SIGNAL(valueChanged(int)),this,SLOT(SlotOnBrightnessChanged(int)));
    QObject::connect(ui.hsldContrast,SIGNAL(valueChanged(int)),this,SLOT(SlotOnContrastChanged(int)));
    QObject::connect(ui.hsldSaturation,SIGNAL(valueChanged(int)),this,SLOT(SlotOnSaturationChanged(int)));
    QObject::connect(ui.hsldSharpness,SIGNAL(valueChanged(int)),this,SLOT(SlotOnSharpnessChanged(int)));
    QObject::connect(ui.hsldHue,SIGNAL(valueChanged(int)),this,SLOT(SlotOnHueChanged(int)));

    QObject::connect(ui.btnGetVAConfig,SIGNAL(clicked()),this,SLOT(SlotOnGetVAConfig()));
    QObject::connect(ui.btnSetVAConfig,SIGNAL(clicked()),this,SLOT(SlotOnSetVAConfig()));

    QObject::connect(ui.btnGetDeviceDetails,SIGNAL(clicked()),this,SLOT(SlotOnGetDeviceDetails()));

    QObject::connect(ui.btnGetSys,SIGNAL(clicked()),this,SLOT(SlotOnGetTimeConfig()));
    QObject::connect(ui.btnSetSys,SIGNAL(clicked()),this,SLOT(SlotOnSetTimeConfig()));

    QObject::connect(ui.btnSetEZoom,SIGNAL(clicked()),this,SLOT(SlotOnSetEZoom()));
    QObject::connect(ui.btnResetEZoom,SIGNAL(clicked()),this,SLOT(SlotOnResetEZoom()));
    
    QObject::connect(ui.btnGetFocusMode,SIGNAL(clicked()),this,SLOT(SlotOnGetFocusConfig()));

    QObject::connect(ui.btnGetIrisConfig,SIGNAL(clicked()),this,SLOT(SlotOnGetIrisConfig()));
    QObject::connect(ui.cbExposureMode,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnExposureModeChanged(int)));
    QObject::connect(ui.cbIris,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnExposureModeChanged(int)));
    QObject::connect(ui.cbShutterLimit,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnExposureModeChanged(int)));
    QObject::connect(ui.cbShutterTimes,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnExposureModeChanged(int)));
    QObject::connect(ui.spinExposureGain,SIGNAL(valueChanged(int)),this,SLOT(SlotOnExposureModeChanged(int)));
    QObject::connect(ui.spinExposureGainLimit,SIGNAL(valueChanged(int)),this,SLOT(SlotOnExposureModeChanged(int)));

    SlotOnExposureModeChanged(-1);

    QObject::connect(ui.cbSyncTime,SIGNAL(stateChanged(int)),this,SLOT(SlotOnSyncTime(int)));

    QObject::connect(ui.cbFocusMode,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotSetFocusConfig(int)));
    QObject::connect(ui.cbMinFocusDis,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotSetFocusConfig(int)));

    QObject::connect(ui.cbWhiteBalance,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnWBGainChanged(int)));

    QObject::connect(ui.hsldGainR,SIGNAL(valueChanged(int)),this,SLOT(SlotOnWBGainChanged(int)));
    QObject::connect(ui.hsldGainB,SIGNAL(valueChanged(int)),this,SLOT(SlotOnWBGainChanged(int)));

    QObject::connect(ui.cbVDenoiseEnable,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnVDenoiseChanged(int)));
    QObject::connect(ui.hsld2DLevel,SIGNAL(valueChanged(int)),this,SLOT(SlotOnVDenoiseChanged(int)));
    QObject::connect(ui.hsld3DLevel,SIGNAL(valueChanged(int)),this,SLOT(SlotOnVDenoiseChanged(int)));

    QObject::connect(ui.cbDayNight,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnDayNightChanged(int)));
    QObject::connect(ui.cbDayNightSens,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnDayNightChanged(int)));
    QObject::connect(ui.cbWDR,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnWDRChanged(int)));
    QObject::connect(ui.spinWDRLevel,SIGNAL(valueChanged(int)),this,SLOT(SlotOnWDRChanged(int)));
    QObject::connect(ui.cbMirrorEnable,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnMirrorChanged(int)));
    QObject::connect(ui.cbVideoStandard,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnVideoStandardChanged(int)));
    QObject::connect(ui.cbLocalOutput,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnLocalOutputChanged(int)));

    QObject::connect(ui.btnGetAudioInput,SIGNAL(clicked()),this,SLOT(SlotOnGetAudioInput()));
    QObject::connect(ui.btnSetAudioInput,SIGNAL(clicked()),this,SLOT(SlotOnSetAudioInput()));

    QObject::connect(ui.btnGetOSD,SIGNAL(clicked()),this,SLOT(SlotOnGetOSD()));
    QObject::connect(ui.btnSetOSD,SIGNAL(clicked()),this,SLOT(SlotOnSetOSD()));

    QObject::connect(ui.btnGetDDNS,SIGNAL(clicked()),this,SLOT(SlotOnGetDDNS()));
    QObject::connect(ui.btnSetDDNS,SIGNAL(clicked()),this,SLOT(SlotOnSetDDNS()));

    QObject::connect(ui.btnGetPPP,SIGNAL(clicked()),this,SLOT(SlotOnGetPPPoE()));
    QObject::connect(ui.btnSetPPP,SIGNAL(clicked()),this,SLOT(SlotOnSetPPPoE()));

    QObject::connect(ui.btnGetFTP,SIGNAL(clicked()),this,SLOT(SlotOnGetFtp()));
    QObject::connect(ui.btnSetFTP,SIGNAL(clicked()),this,SLOT(SlotOnSetFtp()));

    QObject::connect(ui.btnGetUPnP,SIGNAL(clicked()),this,SLOT(SlotOnGetUPnP()));
    QObject::connect(ui.btnSetUPnP,SIGNAL(clicked()),this,SLOT(SlotOnSetUPnP()));

    QObject::connect(ui.btnGetPortConfig,SIGNAL(clicked()),this,SLOT(SlotOnGetPort()));
    QObject::connect(ui.btnSetPortConfig,SIGNAL(clicked()),this,SLOT(SlotOnSetPort()));
    
    QObject::connect(ui.btnGetEmail,SIGNAL(clicked()),this,SLOT(SlotOnGetEmail()));
    QObject::connect(ui.btnSetEmail,SIGNAL(clicked()),this,SLOT(SlotOnSetEmail()));

    QObject::connect(ui.btnGetAuth,SIGNAL(clicked()),this,SLOT(SlotOnGetAuth()));
    QObject::connect(ui.btnSetAuth,SIGNAL(clicked()),this,SLOT(SlotOnSetAuth()));
    
    QObject::connect(ui.btnSaveMotionTrigger,SIGNAL(clicked()),this,SLOT(SlotSaveMotionTrigger()));

    QObject::connect(ui.btnSaveAlarmSchedule,SIGNAL(clicked()),this,SLOT(SlotOnSaveSchedule()));
    QObject::connect(ui.btnSaveRecordSchedule,SIGNAL(clicked()),this,SLOT(SlotOnSaveRecSchedule()));

    QObject::connect(ui.cbbRecScheduleDay,SIGNAL(currentIndexChanged(int)),this,SLOT(HandleRecordSchedule(int)));

    QObject::connect(ui.cbbDDNSAlias,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnDDNSAliasChanged(int)));

    QObject::connect(ui.cbFTPAnonymous,SIGNAL(stateChanged(int)),this,SLOT(SlotOnFTPAnonyChanged(int)));
    ///////port alarm/////////////////////////////////////////////////////////
    QObject::connect(ui.cbbPortInNum,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnGetPortInput(int)));
    QObject::connect(ui.cbbPortOutNum,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnGetPortOutput(int)));
    QObject::connect(ui.cbbExpType,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnGetException(int)));

    QObject::connect(ui.btnSavePortInTrigger,SIGNAL(clicked()),this,SLOT(SlotSavePortInput()));
    QObject::connect(ui.btnSavePortOut,SIGNAL(clicked()),this,SLOT(SlotSavePortOutput()));
    QObject::connect(ui.btnSaveException,SIGNAL(clicked()),this,SLOT(SlotSaveException()));
    
    QObject::connect(ui.btnReboot,SIGNAL(clicked()),this,SLOT(SlotOnReboot()));
    QObject::connect(ui.btnSimpleRestore,SIGNAL(clicked()),this,SLOT(SlotOnSimpleRestore()));
    QObject::connect(ui.btnRestoreFactory,SIGNAL(clicked()),this,SLOT(SlotOnCompleteRestore()));
    //////////////////////////////////////////////////////////////////////////
    ui.cbbTimezone->addItem("GMT-12:00",QVariant(-12.0f));
    ui.cbbTimezone->addItem("GMT-11:00",QVariant(-11.0f));
    ui.cbbTimezone->addItem("GMT-10:00",QVariant(-10.0f));
    ui.cbbTimezone->addItem("GMT-09:00",QVariant(-9.0f));
    ui.cbbTimezone->addItem("GMT-08:00",QVariant(-8.0f));
    ui.cbbTimezone->addItem("GMT-07:00",QVariant(-7.0f));
    ui.cbbTimezone->addItem("GMT-06:00",QVariant(-6.0f));
    ui.cbbTimezone->addItem("GMT-05:00",QVariant(-5.0f));
    ui.cbbTimezone->addItem("GMT-04:30",QVariant(-4.5f));
    ui.cbbTimezone->addItem("GMT-04:00",QVariant(-4.0f));
    ui.cbbTimezone->addItem("GMT-03:30",QVariant(-3.5f));
    ui.cbbTimezone->addItem("GMT-03:00",QVariant(-3.0f));
    ui.cbbTimezone->addItem("GMT-02:00",QVariant(-2.0f));
    ui.cbbTimezone->addItem("GMT-01:00",QVariant(-1.0f));
    ui.cbbTimezone->addItem("GMT+00:00",QVariant(0.0f));
    ui.cbbTimezone->addItem("GMT+01:00",QVariant(1.0f));
    ui.cbbTimezone->addItem("GMT+02:00",QVariant(2.0f));
    ui.cbbTimezone->addItem("GMT+03:00",QVariant(3.0f));
    ui.cbbTimezone->addItem("GMT+03:30",QVariant(3.5f));
    ui.cbbTimezone->addItem("GMT+04:00",QVariant(4.0f));
    ui.cbbTimezone->addItem("GMT+04:30",QVariant(4.5f));
    ui.cbbTimezone->addItem("GMT+05:00",QVariant(5.0f));
    ui.cbbTimezone->addItem("GMT+05:30",QVariant(5.5f));
    ui.cbbTimezone->addItem("GMT+05:45",QVariant(5.75f));
    ui.cbbTimezone->addItem("GMT+06:00",QVariant(6.0f));
    ui.cbbTimezone->addItem("GMT+06:30",QVariant(6.5f));
    ui.cbbTimezone->addItem("GMT+07:00",QVariant(7.0f));
    ui.cbbTimezone->addItem("GMT+08:00",QVariant(8.0f));
    ui.cbbTimezone->addItem("GMT+09:00",QVariant(9.0f));
    ui.cbbTimezone->addItem("GMT+09:30",QVariant(9.5f));
    ui.cbbTimezone->addItem("GMT+10:00",QVariant(10.0f));
    ui.cbbTimezone->addItem("GMT+11:00",QVariant(11.0f));
    ui.cbbTimezone->addItem("GMT+12:00",QVariant(12.0f));
    ui.cbbTimezone->addItem("GMT+13:00",QVariant(13.0f));
    ////////////ir led///////////////////////////////////////////////////////////
    for (unsigned i = 1;i<=10;++i)
    {
        ui.cbbIRNear->addItem(QString::number(i));
        ui.cbbIRFar->addItem(QString::number(i));
        ui.cbbIRSensitivity->addItem(QString::number(i));
    }
    QObject::connect(ui.btnSetIRLed,SIGNAL(clicked()),this,SLOT(SlotOnSetIRLed()));
    ///////////ptz pattern///////////////////////////////////////////////////////
    for (unsigned i = 0;i<4;++i)
    {
        QString temp;
        temp.sprintf("pattern %d",i+1);
        ui.cbbPatternIndex->addItem(temp);
    }
    ui.btnStartPattern->setToolTip("Start Pattern");
    ui.btnStopPattern->setToolTip("Stop Pattern");
    ui.btnStartRecordPattern->setToolTip("Start Record Pattern");
    ui.btnStopRecordPattern->setToolTip("Stop Recrod Pattern");

    QObject::connect(ui.btnStartPattern,SIGNAL(clicked()),this,SLOT(SlotOnStartPattern()));
    QObject::connect(ui.btnStopPattern,SIGNAL(clicked()),this,SLOT(SlotOnStopPattern()));
    QObject::connect(ui.btnStartRecordPattern,SIGNAL(clicked()),this,SLOT(SlotOnStartRecordPattern()));
    QObject::connect(ui.btnStopRecordPattern,SIGNAL(clicked()),this,SLOT(SlotOnStopRecordPattern()));
    ///////////ptz scan///////////////////////////////////////////////////////////////
    for (unsigned i = 0;i<4;++i)
    {
        QString temp;
        temp.sprintf("pattern %d",i+1);
        ui.cbbScanIndex->addItem(temp);
    }
    ui.btnStartScan->setToolTip("Start Scan");
    ui.btnStopScan->setToolTip("Stop Scan");
    ui.btnSetScanLeft->setToolTip("Set Left");
    ui.btnSetScanRight->setToolTip("Set Right");
    ui.btnDeleteScan->setToolTip("Delete Scan");

    QObject::connect(ui.btnStartScan,SIGNAL(clicked()),this,SLOT(SlotOnStartScan()));
    QObject::connect(ui.btnStopScan,SIGNAL(clicked()),this,SLOT(SlotOnStopScan()));
    QObject::connect(ui.btnSetScanLeft,SIGNAL(clicked()),this,SLOT(SlotOnSetScanLeft()));
    QObject::connect(ui.btnSetScanRight,SIGNAL(clicked()),this,SLOT(SlotOnSetScanRight()));
    QObject::connect(ui.btnDeleteScan,SIGNAL(clicked()),this,SLOT(SlotOnDeleteScan()));
    ///////////ptz sequence//////////////////////////////////////////////////////
    for (unsigned i = 0;i<8;++i)
    {
        QString temp;
        temp.sprintf("sequence %d",i+1);
        ui.cbbSequenceIndex->addItem(temp);
    }
    for (unsigned i = 0;i<255;++i)
    {
        ui.cbbSeqPresets->addItem(QString::number(i+1));
    }
    QObject::connect(ui.btnStartSequence,SIGNAL(clicked()),this,SLOT(SlotOnStartSeq()));
    QObject::connect(ui.btnStopSequence,SIGNAL(clicked()),this,SLOT(SlotOnStopSeq()));
    QObject::connect(ui.btnSaveSequence,SIGNAL(clicked()),this,SLOT(SlotOnSaveSeq()));
    QObject::connect(ui.btnDelSequence,SIGNAL(clicked()),this,SLOT(SlotOnDelSeq()));
    QObject::connect(ui.btnAddSeqPreset,SIGNAL(clicked()),this,SLOT(SlotOnAddSeq()));
    QObject::connect(ui.btnClearSeqPresets,SIGNAL(clicked()),this,SLOT(SlotOnClearSeq()));

    QObject::connect(ui.tboxPTZ,SIGNAL(currentChanged(int)),this,SLOT(SlotOnTboxPTZChanged(int)));
    QObject::connect(ui.cbbSequenceIndex,SIGNAL(currentIndexChanged(int)),this,SLOT(SlotOnSeqListChanged(int)));

    ui.ltwSeqPresets->setColumnCount(3);
    ui.ltwSeqPresets->setColumnWidth(0,60);
    ui.ltwSeqPresets->setColumnWidth(1,60);
    ui.ltwSeqPresets->setColumnWidth(2,60);
    ui.ltwSeqPresets->verticalHeader()->setDefaultSectionSize(25);
    ui.ltwSeqPresets->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui.ltwSeqPresets->setHorizontalHeaderItem(0,new QTableWidgetItem("preset"));
    ui.ltwSeqPresets->setHorizontalHeaderItem(1,new QTableWidgetItem("delay"));
    ui.ltwSeqPresets->setHorizontalHeaderItem(2,new QTableWidgetItem("speed"));
    ////////////storage devices////////////////////////////////////////////////////
    ui.ltwStorageDevices->setColumnCount(5);
    ui.ltwStorageDevices->setColumnWidth(0,30);
    ui.ltwStorageDevices->setColumnWidth(1,60);
    ui.ltwStorageDevices->setColumnWidth(2,60);
    ui.ltwStorageDevices->setColumnWidth(3,50);
    ui.ltwStorageDevices->setColumnWidth(4,60);
    ui.ltwStorageDevices->verticalHeader()->setDefaultSectionSize(25);
    ui.ltwStorageDevices->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui.ltwStorageDevices->setHorizontalHeaderItem(0,new QTableWidgetItem(""));
    ui.ltwStorageDevices->setHorizontalHeaderItem(1,new QTableWidgetItem("Capacity"));
    ui.ltwStorageDevices->setHorizontalHeaderItem(2,new QTableWidgetItem("Used"));
    ui.ltwStorageDevices->setHorizontalHeaderItem(3,new QTableWidgetItem("Status"));
    ui.ltwStorageDevices->setHorizontalHeaderItem(4,new QTableWidgetItem("Progress"));

    QObject::connect(ui.btnFormatDevices,SIGNAL(clicked()),this,SLOT(SlotOnFormatDevices()));
    QObject::connect(ui.btnSaveQuota,SIGNAL(clicked()),this,SLOT(SlotOnSaveQuota()));
    
    ////////////Motion Area////////////////////////////////////////////////////////
    QObject::connect(ui.btnClearMotionArea,SIGNAL(clicked()),this,SLOT(SlotOnClearMotionArea()));
    QObject::connect(ui.btnSaveMotionArea,SIGNAL(clicked()),this,SLOT(SlotOnSaveMotionArea()));
    ////////////Users//////////////////////////////////////////////////////////////
    ui.ltwUsers->setColumnCount(3);
    ui.ltwUsers->setColumnWidth(0,35);
    ui.ltwUsers->setColumnWidth(1,85);
    ui.ltwUsers->setColumnWidth(2,70);
    ui.ltwUsers->verticalHeader()->setDefaultSectionSize(20);
    ui.ltwUsers->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui.ltwUsers->setHorizontalHeaderItem(0,new QTableWidgetItem("num"));
    ui.ltwUsers->setHorizontalHeaderItem(1,new QTableWidgetItem("name"));
    ui.ltwUsers->setHorizontalHeaderItem(2,new QTableWidgetItem("level"));

    QObject::connect(ui.btnDelUser,SIGNAL(clicked()),this,SLOT(SlotDeleteUser()));
    QObject::connect(ui.btnSetUser,SIGNAL(clicked()),this,SLOT(SlotSetUser()));
    QObject::connect(ui.btnGetUsers,SIGNAL(clicked()),this,SLOT(SlotGetUsers()));
    QObject::connect(ui.ltwUsers,SIGNAL(cellClicked(int,int)),this,SLOT(SlotClickUserList(int,int)));
    //////IP Filter////////////////////////////////////////////////////////////////////
    ui.ltwIPFilterList->setColumnCount(2);
    ui.ltwIPFilterList->setColumnWidth(0,35);
    ui.ltwIPFilterList->setColumnWidth(1,150);
    ui.ltwIPFilterList->verticalHeader()->setDefaultSectionSize(20);
    ui.ltwIPFilterList->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui.ltwIPFilterList->setRowCount(0);
    ui.ltwIPFilterList->setHorizontalHeaderItem(0,new QTableWidgetItem("Num"));
    ui.ltwIPFilterList->setHorizontalHeaderItem(1,new QTableWidgetItem("IP"));

    QObject::connect(ui.btnGetIPFilter,SIGNAL(clicked()),this,SLOT(SlotOnGetIPFilter()));
    QObject::connect(ui.btnDeleteIP,SIGNAL(clicked()),this,SLOT(SlotOnDeleteIPFilter()));
    QObject::connect(ui.btnAddIPFilter,SIGNAL(clicked()),this,SLOT(SlotOnAddIPFilter()));
    //////////debug view/////////////////////////////////////////////////////////
    qdbg_ = new QDebugview(NULL);
    qdbg_->setWindowFlags(Qt::WindowStaysOnTopHint);
    qdbg_->setWindowFlags(qdbg_->windowFlags()& ~Qt::WindowMaximizeButtonHint& ~Qt::WindowMinimizeButtonHint);
    //qdbg_->show();

    //////////////////////////////////////////////////////////////////////////
    ui_playback_ = new QRemotePlayback(NULL);
    //ui_playback_->setWindowFlags(Qt::WindowStaysOnTopHint);
    ui_playback_->setWindowFlags(ui_playback_->windowFlags()& ~Qt::WindowMaximizeButtonHint& ~Qt::WindowMinimizeButtonHint);
    //////////sdk////////////////////////////////////////////////////////////////
    CreateDevice();    
    setFocusPolicy(Qt::StrongFocus);

    //////////////////////////////////////////////////////////////////////////
    timer_move_stop_ = new QTimer(this);
    QObject::connect(timer_move_stop_,SIGNAL(timeout()),this,SLOT(DoPTZStop()));
    timer_move_stop_->setSingleShot(true);

    timer_restart_recv_message_ = new QTimer(this);
    QObject::connect(timer_restart_recv_message_,SIGNAL(timeout()),this,SLOT(DoRestartRecvMessage()));
    timer_restart_recv_message_->setSingleShot(true);

    timer_get_storage_devices_ = new QTimer(this);
    QObject::connect(timer_get_storage_devices_,SIGNAL(timeout()),this,SLOT(TimerGetStorageDevices()));
    timer_get_storage_devices_->setSingleShot(true);

    timer_test_media_ = new QTimer(this);
    QObject::connect(timer_test_media_,SIGNAL(timeout()),this,SLOT(OnTimerTestMedia()));
    timer_test_media_->setSingleShot(false);

    //////////////////////////////////////////////////////////////////////////
    QObject::connect(ui.cbbScheduleDay,SIGNAL(currentIndexChanged(int)),this,SLOT(HandleAlarmSchedule(int)));
    QObject::connect(ui.cbbScheduleType,SIGNAL(currentIndexChanged(int)),this,SLOT(HandleAlarmScheduleType(int)));
    QObject::connect(ui.cbbScheduleChannel,SIGNAL(currentIndexChanged(int)),this,SLOT(HandleAlarmScheduleType(int)));

    QObject::connect(ui.tabConfigPage,SIGNAL(currentChanged(int)),this,SLOT(SlotOnTabPageChanged(int)));
    QObject::connect(ui.tbCameraConfig,SIGNAL(currentChanged(int)),this,SLOT(SlotOnCameraPageChanged(int)));
    QObject::connect(ui.tbVAConfig,SIGNAL(currentChanged(int)),this,SLOT(SlotOnVAPageChanged(int)));

    ui.tabConfigPage->setCurrentIndex(0);
    ui.tboxPTZ->setCurrentIndex(0);
    ui.tbCameraConfig->setCurrentIndex(0);
}

void multi_ipnc_demo::OnlineTreeViewDoubleClick( const QModelIndex & index )
{
    if (index.parent().isValid())
    {
        DoConnect();
    }
}

void multi_ipnc_demo::OnlineTreeViewClick( const QModelIndex & index )
{
    if (index.parent().isValid())
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            OnVideoPanelMousePress(video_widget_[nsst_channel.channel][nsst_channel.stream]->video_panel_label_);
        }
    }
}

void multi_ipnc_demo::OnVideoPanelMousePress( QVideoPanelLabel* panel_label )
{
    for (unsigned i = 0;i < MAX_CHANNEL;++i)
    {
        for (unsigned j = 0;j < MAX_STREAM_PER_CHANNEL;++j)
        {
            if (video_widget_[i][j]->video_panel_label_ != panel_label)
            {
                video_widget_[i][j]->SetPanelNoActive();
            }
            else
            {
                int row = i*MAX_STREAM_PER_CHANNEL+j;
                video_widget_[i][j]->SetPanelActive();
                QModelIndex index = ui.treev_ipnc->model()->index(row,0,ui.treev_ipnc->model()->index(0,0)); 
                ui.treev_ipnc->setCurrentIndex(index);
                //ui.treev_ipnc->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
            }
        }
    }
}

void multi_ipnc_demo::CreateDevice()
{
    NsstDevice device;
    strcpy(device.host,device_info_.device_ip.toUtf8().data());
    strcpy(device.username,device_info_.device_username.toUtf8().data());
    strcpy(device.password,device_info_.device_password.toUtf8().data());
    device.protocol_port = device_info_.device_port;
    device.rtsp_port = device_info_.device_rtspport;
    device.dev_type = (NSST_DEVICE_TYPE)device_info_.device_type;
    device_id_ = NSSTCreateDevice(&device,NULL);
    qdbg_->id(device_id_);
    ui_playback_->id(device_id_);
    for (unsigned i = 0;i < MAX_CHANNEL;++i)
    {
        for (unsigned j = 0;j < MAX_STREAM_PER_CHANNEL;++j)
        {
            video_widget_[i][j]->ResetDeviceId(device_id_);
        }
    }
}

void multi_ipnc_demo::ReleaseDevice()
{
    DoLogout();
    NSSTReleaseDevice(device_id_);
    device_id_ = -1;
}

void multi_ipnc_demo::OnTreeContextMenuRequested( const QPoint &pos )
{
    QModelIndex index = ui.treev_ipnc->currentIndex();
    if (index.parent().isValid())
    {
        menu_channel_->exec(QCursor::pos());
    }
    else
    {
        menu_device_->exec(QCursor::pos());
    }
}

void multi_ipnc_demo::DoLogin()
{
    if (device_id_ >= 0)
    {
        NSSTLogin(device_id_);
    }
}

void multi_ipnc_demo::DoLogout()
{
    timer_restart_recv_message_->stop();
    if (device_id_ >= 0)
    {
        NSSTLogout(device_id_);
        QString show;
        show.sprintf("LOGOUT(id = %d)",device_id_);
        ShowStatus(STATUS_LOG_WARNING,show);

        for (unsigned i = 0;i < MAX_CHANNEL;++i)
        {
            for (unsigned j = 0;j < MAX_STREAM_PER_CHANNEL;++j)
            {
                video_widget_[i][j]->CloseVideo();
            }
        }
    }
}

void multi_ipnc_demo::DoConnect()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        PlayVideo(&nsst_channel);
    }
}

void multi_ipnc_demo::DoDisconnect()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        CloseVideo(&nsst_channel);
    }
}

void multi_ipnc_demo::DoConnectAll()
{
    for (unsigned i = 0;i < MAX_CHANNEL;++i)
    {
        for (unsigned j = 0;j < MAX_STREAM_PER_CHANNEL;++j)
        {
            NsstChannel nsst_channel;
            nsst_channel.dev_id = device_id_;
            nsst_channel.channel = i;
            nsst_channel.stream = j;
            PlayVideo(&nsst_channel);
        }
    }
}

void multi_ipnc_demo::DoDisconnectAll()
{
    for (unsigned i = 0;i < MAX_CHANNEL;++i)
    {
        for (unsigned j = 0;j < MAX_STREAM_PER_CHANNEL;++j)
        {
            NsstChannel nsst_channel;
            nsst_channel.dev_id = device_id_;
            nsst_channel.channel = i;
            nsst_channel.stream = j;
            CloseVideo(&nsst_channel);
        }
    }
}

void multi_ipnc_demo::PlayVideo( NsstChannel* nsst_channel )
{
    video_widget_[nsst_channel->channel][nsst_channel->stream]->PlayVideo();
}

void multi_ipnc_demo::CloseVideo( NsstChannel* nsst_channel )
{
    video_widget_[nsst_channel->channel][nsst_channel->stream]->CloseVideo();
}

bool multi_ipnc_demo::GetSelectedStreamInfo( NsstChannel* nsst_channel )
{
    QModelIndex index = ui.treev_ipnc->currentIndex();
    nsst_channel->dev_id = device_id_;
    if (index.parent().isValid())
    {
        QModelIndex index = ui.treev_ipnc->currentIndex();
        if (index.row() == 0)
        {
            nsst_channel->channel = 0;
            nsst_channel->stream = 0;
            return true;
        }
        else if (index.row() == 1)
        {
            nsst_channel->channel = 0;
            nsst_channel->stream = 1;
            return true;
        }
        else if (index.row() == 2)
        {
            nsst_channel->channel = 1;
            nsst_channel->stream = 0;
            return true;
        }
        else if (index.row() == 3)
        {
            nsst_channel->channel = 1;
            nsst_channel->stream = 1;
            return true;
        }
    }
    return false;
}

void multi_ipnc_demo::ShowStatus( STATUS_LOG_LEVEL level,const QString& qstr )
{
    QTime now;
    switch (level)
    {
    case STATUS_LOG_NORMAL:
        ui.tedtLog->append(QString("<font color=black>%1 : %2</font>").arg(now.currentTime().toString()).arg(qstr));
    	break;
    case STATUS_LOG_WARNING:
        ui.tedtLog->append(QString("<font color=blue>%1 : %2</font>").arg(now.currentTime().toString()).arg(qstr));
        break;
    case STATUS_LOG_ERROR:
        ui.tedtLog->append(QString("<font color=red>%1 : %2</font>").arg(now.currentTime().toString()).arg(qstr));
        break;
    }
}

void multi_ipnc_demo::OnVideoPanelDblClick( QVideoPanelLabel* panel_label )
{
    int index = 0;
    for (unsigned i = 0;i < MAX_CHANNEL;++i)
    {
        for (unsigned j = 0;j < MAX_STREAM_PER_CHANNEL;++j)
        {
            if (video_widget_[i][j]->video_panel_label_ != panel_label)
            {
                grid_show_full_ ? video_widget_[i][j]->show() : video_widget_[i][j]->hide();
            }

            ++index;
        }
    }

    grid_show_full_ = !grid_show_full_; 
}

void multi_ipnc_demo::OnFullScreenClick()
{
    
    if (client_show_full_)
    {
        //showNormal();
        ui.groupBox->setParent(this);
        ui.groupBox->showNormal();
        ui.horizontalLayout->insertWidget(1,ui.groupBox);
        this->show();
        this->setFocus();
    }
    else
    {
        ui.groupBox->setParent(NULL);
        ui.groupBox->showFullScreen();
        this->hide();
        //showFullScreen();
    }
    client_show_full_ = !client_show_full_;
}

void multi_ipnc_demo::resizeEvent( QResizeEvent * ev)
{

}

void multi_ipnc_demo::SlotOnVideoKeyPress( int key )
{
    bool ptz = false;
    switch (key)
    {
    case Qt::Key_Escape:
        {
            if (client_show_full_)
            {
                OnFullScreenClick();
            }
    	    break;
        }
    case Qt::Key_Up:
        {
            if (!timer_move_stop_->isActive())
            {
                OnPTZUpPress();
            }
            ptz = true;
            break;
        }
    case Qt::Key_Down:
        {
            if (!timer_move_stop_->isActive())
            {
                OnPTZDownPress();
            }
            
            ptz = true;
            break;
        }
    case Qt::Key_Left:
        {
            if (!timer_move_stop_->isActive())
            {
                OnPTZLeftPress();
            }
            
            ptz = true;
            break;
        }
    case Qt::Key_Right:
        {
            if (!timer_move_stop_->isActive())
            {
                OnPTZRightPress();
            }
            
            ptz = true;
            break;
        }
    default:
        break;
    }

    if (ptz)
    {
        timer_move_stop_->stop();
        timer_move_stop_->start(100);
    }
}

void multi_ipnc_demo::OnVideoStatusShowHideClick()
{
    for (unsigned i = 0;i < MAX_CHANNEL;++i)
    {
        for (unsigned j = 0;j < MAX_STREAM_PER_CHANNEL;++j)
        {
            video_widget_[i][j]->video_form_.widgetStatus->setVisible(!video_widget_[i][j]->video_form_.widgetStatus->isVisible());
        }
    }
}

void multi_ipnc_demo::SlotOnSDKCommonEvent( int event_type,NsstEventCommonParam* event_param )
{
    QString show;
    if (event_type > NSSTEV_MEDIA_BEGIN && event_type < NSSTEV_MEDIA_END)
    {
        if (!NSSTIsRealtimeChannel(&event_param->nsst_channel))
        {
            //vod message
            ui_playback_->OnSDKMessage(event_type,event_param);
            return;
        }
    }

    if (event_type == NSSTEV_JPEG_PROGRESS)
    {
        ui_playback_->OnGetJPEGProgress(event_param->ival[0],
            event_param->ival[1],event_param->ival[2]);
        return;
    }
    else if (event_type == NSSTEV_JPEG_RESULT)
    {
        ui_playback_->OnJPEGResult(event_param->result);
        return;
    }

    switch (event_type)
    {
    case NSSTEV_LOGIN:
        {
            if (NSST_SUCCESS == event_param->result)
            {
                NsstDeviceDetails* temp = (NsstDeviceDetails*)event_param->pval;
                memcpy(&device_details_,temp,sizeof(NsstDeviceDetails));
                show.sprintf("LOGIN SUCCESS(id = %d)",event_param->nsst_channel.dev_id);
                NSSTStartRecvDevMessage(device_id_);
                ShowStatus(STATUS_LOG_WARNING,show);
            }
            else
            {
                show.sprintf("LOGIN FAILED(id = %d).Error %d",event_param->nsst_channel.dev_id,event_param->result);
                ShowStatus(STATUS_LOG_ERROR,show);
            }
            break;
        }
    case NSSTEV_MEDIA_CONNECTED:
        {
            show.sprintf("MEDIA CONNECTED(id = %d) Channel %d,Stream %d",
                event_param->nsst_channel.dev_id,
                event_param->nsst_channel.channel,
                event_param->nsst_channel.stream);
            ShowStatus(STATUS_LOG_WARNING,show);
            break;
        }
    case NSSTEV_MEDIA_RECONNECTING:
        {
            show.sprintf("MEDIA RECONNECTING(id = %d) Channel %d,Stream %d",
                event_param->nsst_channel.dev_id,
                event_param->nsst_channel.channel,
                event_param->nsst_channel.stream);
            ShowStatus(STATUS_LOG_WARNING,show);
            break;
        }
    case NSSTEV_MEDIA_ERROR:
        {
            show.sprintf("MEDIA NET ERROR(id = %d) Channel %d,Stream %d",
                event_param->nsst_channel.dev_id,
                event_param->nsst_channel.channel,
                event_param->nsst_channel.stream);
            ShowStatus(STATUS_LOG_ERROR,show);
            video_widget_[event_param->nsst_channel.channel][event_param->nsst_channel.stream]->update();
            video_widget_[event_param->nsst_channel.channel][event_param->nsst_channel.stream]->StopRecord();
            break;
        }
    case NSSTEV_TALK_CONNECTED:
        {
            show.sprintf("TALK CONNECTED(id = %d)",
                event_param->nsst_channel.dev_id);
            ShowStatus(STATUS_LOG_WARNING,show);
            break;
        }
    case NSSTEV_TALK_DEVICE_ERROR:
        {
            show.sprintf("TALK FAILED.DEVICE ERROR(id = %d)",
                event_param->nsst_channel.dev_id);
            ShowStatus(STATUS_LOG_ERROR,show);
            break;
        }
    case NSSTEV_TALK_NET_ERROR:
        {
            show.sprintf("TALK FAILED.NET ERROR(id = %d)",
                event_param->nsst_channel.dev_id);
            ShowStatus(STATUS_LOG_ERROR,show);
            break;
        }
    case NSSTEV_MSG_ALARM:
        {
             NsstAlarmInfo* info = (NsstAlarmInfo*)event_param->pval;
             for (unsigned j = 0;j < MAX_STREAM_PER_CHANNEL;++j)
             {
                 video_widget_[info->channel][j]->OnAlarm(info->type,info->status);
             }
             break;
        }
    case NSSTEV_RECV_MESSAGE_ERROR:
        {
            timer_restart_recv_message_->stop();
            timer_restart_recv_message_->start(5000);
            show.sprintf("ALARM pipe error,retry again after 5 seconds.");
            ShowStatus(STATUS_LOG_ERROR,show);
            break;
        }
    case NSSTEV_CMDRV_DEAD_PIXEL:
        {
            qdbg_->OnDeadPixelResult(event_param->result);
            break;
        }
    case NSSTEV_CMDRV_GET_MAC:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                ShowStatus(STATUS_LOG_WARNING,"Get mac address success.");
                ui.edtMacAddress->setText(event_param->sval);
            }
            else
            {
                ShowStatus(STATUS_LOG_ERROR,"Get mac address failed.");
            }
            break;
        }
    case NSSTEV_CMDRV_FORMAT:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                ShowStatus(STATUS_LOG_WARNING,"Formatting...");
            }
            else
            {
                ShowStatus(STATUS_LOG_ERROR,"Format failed.");
            }
            break;
        }
    case NSSTEV_CMDRV_SET_MAC:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                ShowStatus(STATUS_LOG_WARNING,"Set mac address success.");
            }
            else
            {
                ShowStatus(STATUS_LOG_ERROR,"Set mac address failed.");
            }
            
            break;
        }
    case NSSTEV_CMDRV_DEVICE_DETAILS:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                NsstDeviceDetails* details = (NsstDeviceDetails*)event_param->pval;
                ui.edtDeviceModel->setText(details->model);
                ui.edtDeviceSerial->setText(details->serial);
                ui.edtHardwareVersion->setText(details->firmware_ver);
                ui.edtSoftwareVersion->setText(details->software_ver);
                ui.edtWebVersion->setText(details->web_ver);
                ui.edtPluginVersion->setText(details->plugin_ver);
                ui.edtChannelCount->setText(QString::number(details->channel_cnt));
                ui.edtDiskCount->setText(QString::number(details->harddisk_cnt));
                ui.edtAlarmInCount->setText(QString::number(details->alarm_input));
                ui.edtAlarmOutCount->setText(QString::number(details->alarm_output));
                
                ShowStatus(STATUS_LOG_WARNING,"Get device details success.");
            }
            else
            {
                ShowStatus(STATUS_LOG_ERROR,"Get device details failed.");
            }

            break;
        }
    case NSSTEV_CMDRV_SEARCH_FILE:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                NsstMediaFileList* filelist = (NsstMediaFileList*)event_param->pval;
                ui_playback_->OnSearchResult(filelist);
            }
            else
            {
                ShowStatus(STATUS_LOG_ERROR,"Search files failed.");
            }
            break;
        }
    case NSSTEV_CMDRV_USER_MANAGE:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.ltwUsers->setRowCount(0);
                    NsstUserManage* users = (NsstUserManage*)event_param->pval;
                    if (users)
                    {
                        int count = event_param->ival[0];
                        ui.ltwUsers->setRowCount(count);
                        for (int i = 0;i<count;++i)
                        {
                            ui.ltwUsers->setItem(i,0,new QTableWidgetItem(QString::number(i+1)));
                            ui.ltwUsers->setItem(i,1,new QTableWidgetItem(users[i].old_name));
                            ui.ltwUsers->setItem(i,2,new QTableWidgetItem(QString::number(users[i].level)));
                        }
                    }
                }
                else
                {
                    SlotGetUsers();
                }
            }
            ShowCommonLog(event_param,"user manage");
            break;
        }
    case NSSTEV_CMDRV_ALARM_TRIGGER:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstAlarmTrigger* trigger = (NsstAlarmTrigger*)event_param->pval;
                    HandleAlarmTrigger(trigger,event_param->nsst_channel.channel);
                }
            }
            ShowCommonLog(event_param,"alarm trigger");
            break;
        }
    case NSSTEV_CMDRV_PORT_ALARM:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstPortAlarm* config = (NsstPortAlarm*)event_param->pval;
                    if (config->type == 0)
                    {
                        if (ui.cbbPortInNum->currentIndex() == event_param->nsst_channel.channel)
                        {
                            ui.cbPortInputEnable->setCheckState(QT_CHECK_STATE(config->enable));
                            ui.cbbPortInStatus->setCurrentIndex(config->status);
                            ui.PortInName->setText(QString::fromUtf8(config->title));
                        }
                    }
                    else
                    {
                        if (ui.cbbPortOutNum->currentIndex() == event_param->nsst_channel.channel)
                        {
                            ui.cbbPortOutStatus->setCurrentIndex(config->status);
                            ui.PortOutName->setText(QString::fromUtf8(config->title));
                        }  
                    }
                }
            }
            ShowCommonLog(event_param,"port alarm");
            break;
        }
    case NSSTEV_CMDRV_ALARM_SCHEDULE:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstAlarmSchedule* schedule = (NsstAlarmSchedule*)event_param->pval;
                    if (schedule->alarm_type == ui.cbbScheduleType->currentIndex()
                        && event_param->nsst_channel.channel == ui.cbbScheduleChannel->currentIndex())
                    {
                        memcpy(&alarm_schedule_[schedule->alarm_type],schedule,sizeof(NsstAlarmSchedule));
                        HandleAlarmSchedule(-1);
                    }
                }
            }
            ShowCommonLog(event_param,"alarm schedule");
            break;
        }
    case NSSTEV_CMDRV_RECORD_SCHEDULE:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstRecordSchedule* schedule = (NsstRecordSchedule*)event_param->pval;
                    memcpy(&record_schedule_,schedule,sizeof(NsstRecordSchedule));
                    HandleRecordSchedule(-1);
                }
            }
            ShowCommonLog(event_param,"record schedule");
            break;
        }
    case NSSTEV_CMDRV_IP_FILTER:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.ltwIPFilterList->setRowCount(0);
                    NsstIPFilter* filter = (NsstIPFilter*)event_param->pval;
                    if (filter)
                    {
                        int count = filter->count;
                        ui.ltwIPFilterList->setRowCount(count);
                        ui.cbbIPFilter->setCheckState(QT_CHECK_STATE(filter->enable));
                        ui.cbbIPFilterMode->setCurrentIndex(filter->mode);
                        for (int i = 0;i<count;++i)
                        {
                            ui.ltwIPFilterList->setItem(i,0,new QTableWidgetItem(QString::number(i+1)));
                            ui.ltwIPFilterList->setItem(i,1,new QTableWidgetItem(filter->list[i]));
                        }
                    }
                }
            }
            ShowCommonLog(event_param,"ip filter");
            break;
        }
    case NSSTEV_CMDRV_OSD:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstOSD* config = (NsstOSD*)event_param->pval;
                    QString draw_str;
                    if (NS_OSD_DATETIME == config->osd_type)
                    {
                        ui.cbDisplayDate->setCheckState(config->enable ? Qt::Checked : Qt::Unchecked);
                        ui.cbOSDTimeFormat->setCurrentIndex(config->time_format);
                        ui.cbOSDDateFormat->setCurrentIndex(config->date_format);
                        draw_str = QDateTime::currentDateTime().toString(Qt::ISODate);
                    }
                    else if (NS_OSD_CHANNEL_NAME == config->osd_type)
                    {
                        draw_str = QString::fromUtf8(config->text);
                        ui.cbDisplayName->setCheckState(config->enable ? Qt::Checked : Qt::Unchecked);
                        ui.edtChannelName->setText(draw_str);
                    }
                    else
                    {
                        draw_str = QString::fromUtf8(config->text);
                        ui.cbDisplayOSD->setCheckState(config->enable ? Qt::Checked : Qt::Unchecked);
                        ui.textOSD->setText(draw_str);
                    }

                    int channel = event_param->nsst_channel.channel;
                    POINT pos;
                    pos.x = config->x;
                    pos.y = config->y;
                    video_widget_[channel][0]->StartDrawText(
                        (int)config->osd_type,&pos,draw_str);
                }
                else
                {
                    SlotOnGetOSD();
                }
            }
            ShowCommonLog(event_param,"OSD");
            break;
        }
    case NSSTEV_CMDRV_FRAMERATE:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.cbFramerate->setCurrentIndex(event_param->ival[0]-1);
                }
            }
            ShowCommonLog(event_param,"framerate");
            break;
        }  
    case NSSTEV_CMDRV_OUTPUT_DELAY:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.spinOutputDelay->setValue(event_param->ival[0]);
                }
            }
            ShowCommonLog(event_param,"output delay");
            break;
        } 
    case NSSTEV_CMDRV_MOTION_AREA:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    int stream = 0;
                    int channel = event_param->nsst_channel.channel;
                    NsstChannel nsst_channel;
                    if (GetSelectedStreamInfo(&nsst_channel))
                    {
                        if (channel == nsst_channel.channel)
                        {
                            stream = nsst_channel.stream;
                        }
                    }
                    video_widget_[channel][stream]->SetAllAlarmGrid(event_param->ival);
                }
            }
            ShowCommonLog(event_param,"motion alarm area");
            break;
        } 
    case NSSTEV_CMDRV_MOTION_CONFIG:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.cbbMotionEnable->setCheckState(QT_CHECK_STATE(event_param->ival[0]));
                    ui.spinMotionSensitivity->setValue(event_param->ival[1]);
                }
            }
            ShowCommonLog(event_param,"motion alarm");
            break;
        } 
    case NSSTEV_CMDRV_RTSP_AUTH:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.cbbRTSPAuth->setCurrentIndex(event_param->ival[0]);
                }
            }
            ShowCommonLog(event_param,"rtsp auth");
            break;
        } 
    case NSSTEV_CMDRV_ANONYMOUS:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.cbbAnonymous->setCurrentIndex(event_param->ival[0]);
                }
            }
            ShowCommonLog(event_param,"anonymous");
            break;
        } 
    case NSSTEV_CMDRV_AUDIO_INPUT:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.cbbAudioInput->clear();
                    if (event_param->ival[0])
                    {
                        ui.cbbAudioInput->addItem("line",QVariant(0));
                    }
                    if (event_param->ival[1])
                    {
                        ui.cbbAudioInput->addItem("mic",QVariant(1));
                    }
                    int index = ui.cbbAudioInput->findData(QVariant(event_param->ival[2])); 
                    if (index >= 0)
                    {
                        ui.cbbAudioInput->setCurrentIndex(index);
                    }
                    ui.spinAudioInputVolume->setValue(event_param->ival[3]);
                }
            }
            ShowCommonLog(event_param,"audio input");

            break;
        }   
    case NSSTEV_CMDRV_WHITE_BALANCE:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbWhiteBalance,event_param->ival[0]);
                    UNSIGNAL_SET_VALUE(ui.hsldGainR,event_param->ival[1]);
                    UNSIGNAL_SET_VALUE(ui.hsldGainB,event_param->ival[2]);
                    SlotOnWBGainChanged(-1);
                }
            }
            ShowCommonLog(event_param,"white balance");

            break;
        } 
    case NSSTEV_CMDRV_IR_LED:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstIRConfig* config = (NsstIRConfig*)event_param->pval;
                    ui.cbbIRNear->setCurrentIndex(config->near_power-1);
                    ui.cbbIRFar->setCurrentIndex(config->far_power-1);
                    ui.cbbIRCompensation->setCurrentIndex(config->near_compensation);
                    ui.cbbIRSensitivity->setCurrentIndex(config->illuminance-1);
                    ui.cbbPowerAutoControl->setCurrentIndex(config->auto_dimming);
                    ui.cbbIRStatus->setCurrentIndex(config->mode);
                }
            }
            ShowCommonLog(event_param,"ir led");

            break;
        }
    case NSSTEV_CMDRV_FTP:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstFTP* config = (NsstFTP*)event_param->pval;
                    ui.edtFTPAddress->setText(config->svr_address);
                    ui.edtFTPPort->setText(QString::number(config->svr_port));
                    ui.edtFTPUserName->setText(config->username);

                    if (QString(config->username) == "anonymous")
                    {
                        ui.cbFTPAnonymous->setCheckState(Qt::Checked);
                    }
                    else
                    {
                        ui.cbFTPAnonymous->setCheckState(Qt::Unchecked);
                        ui.edtFTPPassword->setText(config->password);
                    }

                    ui.cbFTPDir->setCurrentIndex(config->dir_level_count);
                    ui.cbFTPParentDir->setCurrentIndex(config->dir_level_1);
                    ui.cbFTPChildDir->setCurrentIndex(config->dir_level_2);
                }
            }
            ShowCommonLog(event_param,"ftp");

            break;
        }
    case NSSTEV_CMDRV_EMAIL:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstEmail* config = (NsstEmail*)event_param->pval;
                    ui.edtEmailSName->setText(config->sender_email);
                    ui.edtSMTPPort->setText(QString::number(config->smtp_port));
                    ui.edtEmailSAddress->setText(config->sender_email);
                    ui.edtSMTPServer->setText(config->smtp_server);

                    ui.cbEmailSSL->setCheckState(QT_CHECK_STATE(config->use_ssl));
                    ui.cbEmailAuth->setCheckState(QT_CHECK_STATE(config->auth_enable));

                    ui.edtEmailUserName->setText(config->username);
                    ui.edtEmailPassword->setText(config->password);

                    ui.edtEmailRName0->setText(config->mailto_name[0]);
                    ui.edtEmailRAddress0->setText(config->mailto_email[0]);
                    ui.edtEmailRName1->setText(config->mailto_name[1]);
                    ui.edtEmailRAddress1->setText(config->mailto_email[1]);
                    ui.edtEmailRName2->setText(config->mailto_name[2]);
                    ui.edtEmailRAddress2->setText(config->mailto_email[2]);
                    ui.edtEmailRName3->setText(config->mailto_name[3]);
                    ui.edtEmailRAddress3->setText(config->mailto_email[3]);

                }
            }
            ShowCommonLog(event_param,"E-mail");

            break;
        }
    case NSSTEV_CMDRV_PPPOE:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstPPPoE* config = (NsstPPPoE*)event_param->pval;
                    ui.cbPPPoEEnable->setCheckState(QT_CHECK_STATE(config->enable));
                    ui.edtPPPoEIP->setText(config->ip);
                    ui.edtPPPUserName->setText(config->username);
                    ui.edtPPPPassword->setText(config->password);
                }
            }
            ShowCommonLog(event_param,"pppoe");

            break;
        }

    case NSSTEV_CMDRV_UPNP:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.cbUPnPEnable->setCheckState(QT_CHECK_STATE(event_param->ival[0]));
                    ui.edtUPnPAlias->setText(event_param->sval);
                }
            }
            ShowCommonLog(event_param,"pppoe");

            break;
        }
    case NSSTEV_CMDRV_PTZ_SEQUENCE:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    if (ui.cbbSequenceIndex->currentIndex() == event_param->ival[0])
                    {
                        ui.ltwSeqPresets->setRowCount(0);
                       
                        int count = event_param->ival[1];
                        NsstPTZSequenceItem* item_list = (NsstPTZSequenceItem*)event_param->pval;
                        ui.ltwSeqPresets->setRowCount(count);
                        for (unsigned i = 0;i<event_param->ival[1];++i)
                        {
                            ui.ltwSeqPresets->setItem(i,0,new QTableWidgetItem(QString::number(item_list[i].preset)));
                            ui.ltwSeqPresets->setItem(i,1,new QTableWidgetItem(QString::number(item_list[i].delay)));
                            ui.ltwSeqPresets->setItem(i,2,new QTableWidgetItem(QString::number(item_list[i].speed)));
                        }
                        ui.ltwSeqPresets->update();
                    }
                }
            }
            ShowCommonLog(event_param,"ptz sequence");

            break;
        } 
    case NSSTEV_CMDRV_STORAGE_DEVICES:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.ltwStorageDevices->setRowCount(0);

                    int count = event_param->ival[0];
                    NsstStorageDevice* item_list = (NsstStorageDevice*)event_param->pval;
                    ui.ltwStorageDevices->setRowCount(count);
                    for (unsigned i = 0;i<count;++i)
                    {
                        ui.ltwStorageDevices->setItem(i,0,new QTableWidgetItem(QString::number(item_list[i].index)));
                        ui.ltwStorageDevices->setItem(i,1,new QTableWidgetItem(formatMBytesStr(item_list[i].total)));
                        ui.ltwStorageDevices->setItem(i,2,new QTableWidgetItem(formatMBytesStr(item_list[i].total - item_list[i].used)));
                        ui.ltwStorageDevices->setItem(i,3,new QTableWidgetItem(sd_status_str(item_list[i].status)));
                        ui.ltwStorageDevices->setItem(i,4,new QTableWidgetItem(QString::number(item_list[i].progress)+QString("%")));
                    }
                    ui.ltwStorageDevices->update();
                    timer_get_storage_devices_->start(1000 * 2);
                }
            }
            ShowCommonLog(event_param,"storage devices");

            break;
        }
    case NSSTEV_CMDRV_CAPTURE_CONFIG:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstCaptureConfig* config = (NsstCaptureConfig*)event_param->pval;
                    ui.cbEnableSchCapture->setCheckState(QT_CHECK_STATE(config->enable));
                    QString temp;
                    temp.sprintf("%d*%d",config->width,config->height);
                    ui.edtCaptureResolution->setText(temp.toUtf8().data());
                    ui.cbbCaptureQuality->setCurrentIndex(config->quality);
                    ui.spinCaptureInterval->setValue(config->interval_value);
                    ui.cbbCaptureUnit->setCurrentIndex(config->interval_unit);
                    ui.cbCapToFTP->setCheckState(QT_CHECK_STATE(config->trigger_ftp));
                    ui.cbCapToEmail->setCheckState(QT_CHECK_STATE(config->trigger_email));
                    ui.cbCapToSD->setCheckState(QT_CHECK_STATE(config->trigger_sdcard));
                }
            }
            ShowCommonLog(event_param,"capture config");

            break;
        }
    case NSSTEV_CMDRV_STORAGE_QUOTA:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.edtCaptureCapacity->setText(formatMBytesStr(event_param->ival[0]));
                    ui.edtCaptureFree->setText(formatMBytesStr(event_param->ival[0] - event_param->ival[1]));
                    ui.edtRecordCapacity->setText(formatMBytesStr(event_param->ival[2]));
                    ui.edtRecordFree->setText(formatMBytesStr(event_param->ival[2] - event_param->ival[3]));
                    UNSIGNAL_SET_VALUE(ui.spinCaptureQuota,event_param->ival[4]);
                    ui.spinRecordQuota->setValue(event_param->ival[5]);
                }
            }
            ShowCommonLog(event_param,"storage quota");
            break;
        }
    case NSSTEV_CMDRV_DDNS:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    if (ddnslist_)
                    {
                        delete[] ddnslist_;
                        ddnslist_ = NULL;
                    }

                    int count = event_param->ival[0];
                    NsstDDNS* item_list = (NsstDDNS*)event_param->pval;
                    ui.cbbDDNSAlias->clear();
                    for (unsigned i = 0;i<count;++i)
                    {
                        ui.cbbDDNSAlias->addItem(item_list[i].alias);
                    }

                    if (count > 0)
                    {
                        ddnslist_ = new NsstDDNS[count];
                        memcpy(ddnslist_,item_list,sizeof(NsstDDNS)*count);

                        int index = event_param->ival[1];
                        ui.cbbDDNSAlias->setCurrentIndex(index);

                        ui.cbDDNSEnable->setCheckState(QT_CHECK_STATE(event_param->ival[2]));
                        ui.edtDDNSAddress->setText(item_list[index].address);
                        ui.edtDDNSDomain->setText(item_list[index].domain);
                        ui.edtDDNSPort->setText(QString::number(item_list[index].port));
                        ui.edtDDNSUser->setText(item_list[index].username);
                        ui.edtDDNSPassword->setText(item_list[index].password);
                    }
                }
            }
            ShowCommonLog(event_param,"ddns");

            break;
        } 
    case NSSTEV_CMDRV_FOCUS_CONFIG:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbFocusMode,event_param->ival[0]);
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbMinFocusDis,event_param->ival[1]);
                }
            }
            ShowCommonLog(event_param,"focus config");
            break;
        }
    case NSSTEV_CMDRV_VIDEO_DENOISE:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbVDenoiseEnable,event_param->ival[0]);
                    UNSIGNAL_SET_VALUE(ui.hsld2DLevel,event_param->ival[1]);
                    UNSIGNAL_SET_VALUE(ui.hsld3DLevel,event_param->ival[2]);
                    SlotOnVDenoiseChanged(-1);
                }
            }
            ShowCommonLog(event_param,"video denoise");
            break;
        }
    case NSSTEV_CMDRV_LOCAL_OUTPUT:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbLocalOutput,event_param->ival[0]);
                }
            }
            ShowCommonLog(event_param,"local output");
            break;
        }
    case NSSTEV_CMDRV_VIDEO_STANDARD:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbVideoStandard,event_param->ival[0]);
                }
            }
            ShowCommonLog(event_param,"video standard");
            break;
        }
    case NSSTEV_CMDRV_VIDEO_MIRROR:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbMirrorEnable,event_param->ival[0]);
                }
            }
            ShowCommonLog(event_param,"video mirror");
            break;
        }
    case NSSTEV_CMDRV_WDR:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbWDR,event_param->ival[0]);
                    UNSIGNAL_SET_VALUE(ui.spinWDRLevel,event_param->ival[1]);
                }
            }
            ShowCommonLog(event_param,"WDR");
            break;
        }
    case NSSTEV_CMDRV_DAYNIGHT_SWITCH:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbDayNight,event_param->ival[0]);
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbDayNightSens,event_param->ival[1]);
                }
            }
            ShowCommonLog(event_param,"day night mode");
            break;
        }
    case NSSTEV_CMDRV_TIME_CONFIG:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstTimeConfig* config = (NsstTimeConfig*)event_param->pval;
                    ui.edtNTPAddress->setText(config->ntp_address);
                    ui.edtNTPPort->setText(QString::number(config->ntp_port));
                    ui.spinNTPInterval->setValue(config->ntp_interval);
                    int index = ui.cbbTimezone->findData(QVariant(config->timezone));
                    if (index >= 0)
                    {
                        ui.cbbTimezone->setCurrentIndex(index);
                    }
                    ui.cbNTPEnable->setCheckState(config->ntp_enable > 0 ? Qt::Checked : Qt::Unchecked);
                    QDateTime st = QDateTime::fromTime_t(config->sync_time);
                    ui.edtDeviceTime->setText(st.toUTC().toString(Qt::SystemLocaleShortDate));

                    ui.dtSetTime->setDateTime(QDateTime::currentDateTime());
                }
            }
            ShowCommonLog(event_param,"time config");

            break;
        }
    case NSSTEV_CMDRV_VIDEO_QUALITY:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.cbVideoQuality->setCurrentIndex(event_param->ival[0]);
                }
            }
            ShowCommonLog(event_param,"video quality ");

            break;
        }
    case NSSTEV_CMDRV_IRIS_CONFIG:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstIrisConfig* config = (NsstIrisConfig*)event_param->pval;
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbExposureMode,config->exposure_type);

                    int index = ui.cbShutterLimit->findData(QVariant(config->shutter_limit));
                    if (index >= 0)
                    {
                        UNSIGNAL_SET_CURRENT_INDEX(ui.cbShutterLimit,index);
                    }

                    index = ui.cbShutterTimes->findData(QVariant(config->shutter));
                    if (index >= 0)
                    {
                        UNSIGNAL_SET_CURRENT_INDEX(ui.cbShutterTimes,index);
                    }
                    
                    UNSIGNAL_SET_CURRENT_INDEX(ui.cbIris,config->iris);

                    UNSIGNAL_SET_VALUE(ui.spinExposureGainLimit,config->gain_limit);
                    UNSIGNAL_SET_VALUE(ui.spinExposureGain,config->gain);

                    SlotOnExposureModeChanged(-1);
                }
            }
            ShowCommonLog(event_param,"iris config");

            break;
        }
    case NSSTEV_CMDRV_IFRAME_INTERVAL:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.edtIFrameInterval->setText(QString::number(event_param->ival[0]));
                }
            }
            ShowCommonLog(event_param,"iframe interval");

            break;
        }
    case NSSTEV_CMDRV_BITRATECFG:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.cbBitrateType->setCurrentIndex(event_param->ival[0]);
                    ui.edtMaxBitrate->setText(QString::number(event_param->ival[1]));
                }
            }
            ShowCommonLog(event_param,"bitrate");
            break;
        }
    case NSSTEV_CMDRV_VACONFIG:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    ui.cbStreamType->setCurrentIndex(event_param->ival[0]); 
                    ui.cbEncoding->setCurrentIndex(event_param->ival[3]);
                    if (event_param->ival[1] == 1920 && event_param->ival[2] == 1080)
                    {
                        ui.cbResolution->setCurrentIndex(0);
                    }
                    else if (event_param->ival[1] == 1280 && event_param->ival[2] == 720)
                    {
                        ui.cbResolution->setCurrentIndex(2);
                    }
                    else
                    {
                        ui.cbResolution->setCurrentIndex(1);
                    }
                }
            }
            ShowCommonLog(event_param,"va config");

            break;
        }
    case NSSTEV_CMDRV_CAMERA_PARAMS:
        {
            if (event_param->result == NSST_SUCCESS)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    UNSIGNAL_SET_VALUE(ui.hsldBrightness,event_param->ival[0]);
                    ui.lblBrightness->setText(QString::number(ui.hsldBrightness->value()));

                    UNSIGNAL_SET_VALUE(ui.hsldContrast,event_param->ival[1]);
                    ui.lblContrast->setText(QString::number(ui.hsldContrast->value()));

                    UNSIGNAL_SET_VALUE(ui.hsldSaturation,event_param->ival[2]);
                    ui.lblSaturation->setText(QString::number(ui.hsldSaturation->value()));

                    UNSIGNAL_SET_VALUE(ui.hsldSharpness,event_param->ival[3]);
                    ui.lblSharpness->setText(QString::number(ui.hsldSharpness->value()));

                    UNSIGNAL_SET_VALUE(ui.hsldHue,event_param->ival[4]);
                    ui.lblHue->setText(QString::number(ui.hsldHue->value()));
                }
            }
            ShowCommonLog(event_param,"camera params");
            break;
        }
    case NSSTEV_CMDRV_NET_CONFIG:
        {
            if (event_param->result == 0)
            {
                if (event_param->get_or_set == NS_CMD_GET)
                {
                    NsstNetConfig* net_config = (NsstNetConfig*)event_param->pval;
                    ui.edtIPV4Address->setText(QString::fromAscii(net_config->ipv4_address));
                    ui.edtIPv4DNS->setText(QString::fromAscii(net_config->ipv4_dns_address));
                    ui.edtIPv4Gateway->setText(QString::fromAscii(net_config->ipv4_gateway));
                    ui.edtIPv4Mask->setText(QString::fromAscii(net_config->ipv4_mask));
                    ui.ckbIPv4DHCP->setCheckState(Qt::Checked);

                    ui.cbIPv6Mode->setCurrentIndex(net_config->ipv6_mode);
                    ui.edtIPV6Address->setText(QString::fromAscii(net_config->ipv6_address));
                    ui.edtIPv6Mask->setText(QString::fromAscii(net_config->ipv6_mask));
                    ui.edtIPv6Gateway->setText(QString::fromAscii(net_config->ipv6_gateway));
                    ui.edtIPv6DNS->setText(QString::fromAscii(net_config->ipv6_dns_address));
                }
            }
            ShowCommonLog(event_param,"net config");
            break;
        }
    default:
        break;
    }
}

void multi_ipnc_demo::DoPTZStop()
{
    PTZControl(NS_PTZ_MOVE_STOP);
}

void multi_ipnc_demo::OnPTZUpPress()
{
    PTZControl(NS_PTZ_MOVE_UP);
}

void multi_ipnc_demo::OnPTZAutoClick()
{
    if (!ptz_auto_)
    {
        if (device_id_ >= 0)
        {
            NsstChannel nsst_channel;
            if (GetSelectedStreamInfo(&nsst_channel))
            {
                NSSTPTZScan(&nsst_channel,0,NS_PTZ_SCAN_START,ui.hsldXSpeed->value());
            }
        }
    }
    else
    {
        PTZControl(NS_PTZ_MOVE_STOP);
    }
    ptz_auto_ = !ptz_auto_;
    //PTZControl(NS_PTZ_mo);
}

void multi_ipnc_demo::OnPTZDownPress()
{
    PTZControl(NS_PTZ_MOVE_DOWN);
}

void multi_ipnc_demo::OnPTZLeftPress()
{
    PTZControl(NS_PTZ_MOVE_LEFT);
}

void multi_ipnc_demo::OnPTZRightPress()
{
    PTZControl(NS_PTZ_MOVE_RIGHT);
}

void multi_ipnc_demo::OnPTZLeftTopPress()
{
    PTZControl(NS_PTZ_MOVE_LEFT_UP);
}

void multi_ipnc_demo::OnPTZLeftDownPress()
{
    PTZControl(NS_PTZ_MOVE_LEFT_DOWN);
}

void multi_ipnc_demo::OnPTZRightTopPress()
{
    PTZControl(NS_PTZ_MOVE_RIGHT_UP);
}

void multi_ipnc_demo::OnPTZRightDownPress()
{
    PTZControl(NS_PTZ_MOVE_RIGHT_DOWN);
}

void multi_ipnc_demo::OnPTZIrisOnPress()
{
    PTZControl(NS_PTZ_MOVE_IRIS_OPEN);
}

void multi_ipnc_demo::OnPTZIrisOffPress()
{
    PTZControl(NS_PTZ_MOVE_IRIS_CLOSE);
}

void multi_ipnc_demo::OnPTZWiperOnPress()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTPTZSwitch(&nsst_channel,NS_PTZ_SWITCH_WIPER,1);
    }
}

void multi_ipnc_demo::OnPTZWiperOffPress()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTPTZSwitch(&nsst_channel,NS_PTZ_SWITCH_WIPER,0);
    }
}

void multi_ipnc_demo::OnPTZLightOnPress()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTPTZSwitch(&nsst_channel,NS_PTZ_SWITCH_LIGHT,1);
    }
}

void multi_ipnc_demo::OnPTZLightOffPress()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTPTZSwitch(&nsst_channel,NS_PTZ_SWITCH_LIGHT,0);
    }
}

void multi_ipnc_demo::SlotOnCallPreset()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTPTZPreset(&nsst_channel,NS_PTZ_PRESET_CALL,ui.cbbPreset->currentIndex()+1,"");
    }
}

void multi_ipnc_demo::SlotOnAddPreset()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTPTZPreset(&nsst_channel,NS_PTZ_PRESET_SET,ui.cbbPreset->currentIndex()+1,"");
    }
}

void multi_ipnc_demo::SlotOnDeletePreset()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTPTZPreset(&nsst_channel,NS_PTZ_PRESET_DELETE,ui.cbbPreset->currentIndex()+1,"");
    }
}

void multi_ipnc_demo::SlotShowModifyDeviceInfo()
{
    ui_modify_device_.move((QApplication::desktop()->width() - ui_modify_device_.width())/2,
        (QApplication::desktop()->height() - ui_modify_device_.height())/2); 
    int rv = ui_modify_device_.exec();
    if (1 == rv)
    {
        ReleaseDevice();
        AppSettingsInstance()->GetDeviceInfo(&device_info_);
        CreateDevice();
        first_item_->setText(device_info_.device_ip);
    }
}

void multi_ipnc_demo::SlotOnZoomBig()
{
    PTZControl(NS_PTZ_MOVE_ZOOM_WIDE);
}

void multi_ipnc_demo::SlotOnZoomSmall()
{
    PTZControl(NS_PTZ_MOVE_ZOOM_TELE);
}

void multi_ipnc_demo::SlotOnFocusNear()
{
    PTZControl(NS_PTZ_MOVE_FOCUS_NEAR);
}

void multi_ipnc_demo::SlotOnFocusFar()
{
    PTZControl(NS_PTZ_MOVE_FOCUS_FAR);
}

void multi_ipnc_demo::OnClickUrl( const QUrl & url )
{
    QDesktopServices::openUrl(url);
}

void multi_ipnc_demo::PTZControl( int action )
{
    NsstPTZParam param;
    param.action = action;
    param.speed = ui.hsldXSpeed->value();

    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        QString log;
        log.sprintf("ptz %d",action);
        ShowStatus(STATUS_LOG_NORMAL,log);
        NSSTPTZControl(&nsst_channel,&param);
    }
}

void multi_ipnc_demo::SlotOnSliderSpeedChanged(int speed)
{
    ui.lblXSpeed->setText(QString::number(ui.hsldXSpeed->value()));
}

void multi_ipnc_demo::SlotOnVideoPanelWheel( int channel,int delta )
{
    if (client_show_full_)
    {
        if (timer_move_stop_->isActive())
        {
            PTZControl(delta > 0 ? NS_PTZ_MOVE_ZOOM_WIDE : NS_PTZ_MOVE_ZOOM_TELE);
        }
        
        timer_move_stop_->stop();
        timer_move_stop_->start(100);
    }
}

void multi_ipnc_demo::DoOpenAudio()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTPlayAudio(&nsst_channel);
    }
}

void multi_ipnc_demo::DoCloseAudio()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTCloseAudio(&nsst_channel);
    }
}

void multi_ipnc_demo::SlotOnGetCameraParams()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTGetCameraParams(&nsst_channel);
    }
}

void multi_ipnc_demo::SetCameraParams()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NsstCameraParams camera_params;
        camera_params.brightness = ui.hsldBrightness->value();
        camera_params.contrast = ui.hsldContrast->value();
        camera_params.saturation = ui.hsldSaturation->value();
        camera_params.sharpness = ui.hsldSharpness->value();
        camera_params.hue = ui.hsldHue->value();
        NSSTSetCameraParams(&nsst_channel,&camera_params);
    }
}

void multi_ipnc_demo::SlotOnBrightnessChanged( int val )
{
    ui.lblBrightness->setText(QString::number(ui.hsldBrightness->value()));
}

void multi_ipnc_demo::SlotOnContrastChanged( int val )
{
    ui.lblContrast->setText(QString::number(ui.hsldContrast->value()));
}

void multi_ipnc_demo::SlotOnSaturationChanged( int val )
{
    ui.lblSaturation->setText(QString::number(ui.hsldSaturation->value()));
}

void multi_ipnc_demo::SlotOnSharpnessChanged( int val )
{
    ui.lblSharpness->setText(QString::number(ui.hsldSharpness->value()));
}

void multi_ipnc_demo::SlotOnHueChanged( int val )
{
    ui.lblHue->setText(QString::number(ui.hsldHue->value()));
}

void multi_ipnc_demo::SlotOnGetNetConfig()
{
    if (device_id_ >= 0)
    {
        NSSTGetNetConfig(device_id_);
    }
}

void multi_ipnc_demo::SlotOnSetNetConfig()
{
    if (device_id_ >= 0)
    {
        NsstNetConfig config;
        strcpy_s(config.ipv4_address,ui.edtIPV4Address->text().toAscii().data());
        strcpy_s(config.ipv4_mask,ui.edtIPv4Mask->text().toAscii().data());
        strcpy_s(config.ipv4_gateway,ui.edtIPv4Gateway->text().toAscii().data());
        strcpy_s(config.ipv4_dns_address,ui.edtIPv4DNS->text().toAscii().data());
        config.ipv4_dhcp_enable = ui.ckbIPv4DHCP->checkState();

        strcpy_s(config.ipv6_address,ui.edtIPV6Address->text().toAscii().data());
        strcpy_s(config.ipv6_mask,ui.edtIPv6Mask->text().toAscii().data());
        strcpy_s(config.ipv6_gateway,ui.edtIPv6Gateway->text().toAscii().data());
        strcpy_s(config.ipv6_dns_address,ui.edtIPv6DNS->text().toAscii().data());
        config.ipv6_mode = (NSSTIPV6_MODE)ui.cbIPv6Mode->currentIndex();
        NSSTSetNetConfig(device_id_,&config);
    }
}

void multi_ipnc_demo::SlotOnGetVAConfig()
{
    if (device_id_ >= 0)
    {
        //NSSTGetVAConfig(device_id_);
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTGetFrameRate(&nsst_channel);
            NSSTGetVAConfig(&nsst_channel);
            NSSTGetBitrateConfig(&nsst_channel);
            NSSTGetIFrameInterval(&nsst_channel);
            NSSTGetVideoQuality(&nsst_channel);
        }
    }
}

void multi_ipnc_demo::SlotOnSetVAConfig()
{
    if (device_id_ >= 0)
    {
        //NSSTGetVAConfig(device_id_);
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetFrameRate(&nsst_channel,ui.cbFramerate->currentIndex()+1);

            NsstVAConfig vaconfig;
            vaconfig.stream_type = ui.cbStreamType->currentIndex();
            QString resolution = ui.cbResolution->currentText();
            QStringList rl = resolution.split('*');
            vaconfig.resolution_w = rl[0].toInt();
            vaconfig.resolution_h = rl[1].toInt();
            vaconfig.video_encoding = ui.cbEncoding->currentIndex();
            NSSTSetVAConfig(&nsst_channel,&vaconfig);

            int bitrate_type = ui.cbBitrateType->currentIndex();
            int bitrate_max = ui.edtMaxBitrate->text().toInt();
            NSSTSetBitrateConfig(&nsst_channel,bitrate_type,bitrate_max);

            int interval = ui.edtIFrameInterval->text().toInt();
            NSSTSetIFrameInterval(&nsst_channel,interval);

            int quality = ui.cbVideoQuality->currentIndex();
            NSSTSetVideoQuality(&nsst_channel,quality);
        }
    }
}

void multi_ipnc_demo::SlotOnGetMac()
{
    if (device_id_ >= 0)
    {
        NSSTGetMacAddress(device_id_);
    }
}

void multi_ipnc_demo::SlotOnSetMac()
{
    if (ui.edtMacAddress->text().isEmpty())
    {
        QMessageBox::information(this,"Information",tr("Please input invalid mac first."));
        return;
    }
    if (device_id_ >= 0)
    {
        NSSTSetMacAddress(device_id_,ui.edtMacAddress->text().toAscii().data());
    }
}


void multi_ipnc_demo::DoRestartRecvMessage()
{
    NSSTStartRecvDevMessage(device_id_);
}

void multi_ipnc_demo::OnDebugViewClick()
{
    qdbg_->setWindowFlags(Qt::WindowStaysOnTopHint);
    qdbg_->setWindowFlags(qdbg_->windowFlags()& ~Qt::WindowMaximizeButtonHint& ~Qt::WindowMinimizeButtonHint);
    qdbg_->show();
}

void multi_ipnc_demo::OnPlaybackClick()
{
    //ui_playback_->setWindowFlags(Qt::WindowStaysOnTopHint);
    ui_playback_->setWindowFlags(qdbg_->windowFlags()& ~Qt::WindowMaximizeButtonHint& ~Qt::WindowMinimizeButtonHint);
    ui_playback_->show();
    //ui_playback_->setFocus(Qt::ActiveWindowFocusReason);
}

void multi_ipnc_demo::closeEvent( QCloseEvent * )
{
    QCoreApplication::quit();
}

void multi_ipnc_demo::OnShowFPSClick()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        video_widget_[nsst_channel.channel][nsst_channel.stream]->ShowFps();
    }
}

void multi_ipnc_demo::OnCloseFPSClick()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        video_widget_[nsst_channel.channel][nsst_channel.stream]->CloseFps();
    }
}

void multi_ipnc_demo::SlotOnGetDeviceDetails()
{
    if (device_id_ >= 0)
    {
        NSSTGetDeviceDetails(device_id_);
    }
}

void multi_ipnc_demo::SlotOnGetTimeConfig()
{
    if (device_id_ >= 0)
    {
        NSSTGetTimeConfig(device_id_);
    }
}

void multi_ipnc_demo::SlotOnSetTimeConfig()
{
    if (device_id_ >= 0)
    {
        NsstTimeConfig config;
        if (ui.cbSyncTime->checkState() == Qt::Checked)
        {
            config.sync_time = QDateTime::currentDateTime().toUTC().toTime_t();
        }
        else
        {
            config.sync_time = ui.dtSetTime->dateTime().toUTC().toTime_t();
        }

        config.timezone = ui.cbbTimezone->itemData(ui.cbbTimezone->currentIndex()).toDouble();
        strncpy_s(config.ntp_address,NSST_SHORT_LEN,ui.edtNTPAddress->text().toUtf8().data(),_TRUNCATE);

        config.ntp_port = ui.edtNTPPort->text().toUShort();
        config.ntp_interval = ui.spinNTPInterval->value();
        config.ntp_enable = (ui.cbNTPEnable->checkState() == Qt::Checked) ? 1 : 0;
        NSSTSetTimeConfig(device_id_,&config);
    }
}

void multi_ipnc_demo::SlotOnSyncTime( int state )
{
    if (state == Qt::Checked)
    {
        ui.dtSetTime->setEnabled(false);
    }
    else
    {
        ui.dtSetTime->setEnabled(true);
    }
}

void multi_ipnc_demo::SlotOnGetFocusConfig()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTGetFocusConfig(&nsst_channel);
        }
    }
}

void multi_ipnc_demo::SlotSetFocusConfig( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetFocusConfig(&nsst_channel,ui.cbFocusMode->currentIndex(),ui.cbMinFocusDis->currentIndex());
        }
    }
}

void multi_ipnc_demo::SlotOnGetIrisConfig()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTGetIrisConfig(&nsst_channel);
        }
    }
}

void multi_ipnc_demo::SlotOnSetIrisConfig()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NsstIrisConfig config;
            config.exposure_type = ui.cbExposureMode->currentIndex();
            config.iris = ui.cbIris->currentIndex();
            config.gain = ui.spinExposureGain->value();
            config.gain_limit = ui.spinExposureGainLimit->value();
            config.shutter = ui.cbShutterTimes->itemData(ui.cbShutterTimes->currentIndex()).toInt();
            config.shutter_limit = ui.cbShutterTimes->itemData(ui.cbShutterLimit->currentIndex()).toInt();
            NSSTSetIrisConfig(&nsst_channel,&config);
        }
    }
}

void multi_ipnc_demo::SlotOnExposureModeChanged( int val )
{
    int index = ui.cbExposureMode->currentIndex();
    if (index == 0)
    {
        ui.lblShutterLimit->setVisible(false);
        ui.lblExposureGainLimit->setVisible(false);

        ui.lblIris->setVisible(true);
        ui.lblShutter->setVisible(true);
        ui.lblExposureGain->setVisible(true);

        ui.cbShutterLimit->setVisible(false);
        ui.spinExposureGainLimit->setVisible(false);

        ui.spinExposureGain->setVisible(true);
        ui.cbIris->setVisible(true);
        ui.cbShutterTimes->setVisible(true);
    }
    else if (index == 1)
    {
        ui.lblShutterLimit->setVisible(true);
        ui.lblExposureGainLimit->setVisible(true);

        ui.lblIris->setVisible(false);
        ui.lblShutter->setVisible(false);
        ui.lblExposureGain->setVisible(false);

        ui.cbShutterLimit->setVisible(true);
        ui.spinExposureGainLimit->setVisible(true);

        ui.spinExposureGain->setVisible(false);
        ui.cbIris->setVisible(false);
        ui.cbShutterTimes->setVisible(false);
    }
    else
    {
        ui.lblShutterLimit->setVisible(true);
        ui.lblExposureGainLimit->setVisible(true);

        ui.lblIris->setVisible(true);
        ui.lblShutter->setVisible(false);
        ui.lblExposureGain->setVisible(false);

        ui.cbShutterLimit->setVisible(true);
        ui.spinExposureGainLimit->setVisible(true);

        ui.spinExposureGain->setVisible(false);
        ui.cbIris->setVisible(true);
        ui.cbShutterTimes->setVisible(false);
    }

    if (val >= 0)
    {
        SlotOnSetIrisConfig();
    }
}

void multi_ipnc_demo::SlotOnGetDenoiseConfig()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTGetVideoDenoise(&nsst_channel);
        }
    }
}

void multi_ipnc_demo::SlotOnGetWhiteBalance()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTGetWBConfig(&nsst_channel);
        }
    }
}

void multi_ipnc_demo::SlotOnSetWhiteBalance()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetWBConfig(&nsst_channel,ui.cbWhiteBalance->currentIndex(),ui.hsldGainR->value(),ui.hsldGainB->value());
        }
    }
}

void multi_ipnc_demo::SlotOnGetCameraOthers()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTGetDayNightSwitch(&nsst_channel);
            NSSTGetWDR(&nsst_channel);
            NSSTGetVideoMirror(&nsst_channel);
            NSSTGetVideoStandard(&nsst_channel);
            NSSTGetLocalOutput(&nsst_channel);
        }
    }
}

void multi_ipnc_demo::SlotOnSetCameraOthers()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetDayNightSwitch(&nsst_channel,ui.cbDayNight->currentIndex(),ui.cbDayNightSens->currentIndex());
        }
    }
}


void multi_ipnc_demo::SlotOnCameraPageChanged( int index )
{
    switch (index)
    {
    case 0:
        {
            SlotOnGetCameraParams();
            break;
        }
    case 1:
        {
            SlotOnGetFocusConfig();
            break;
        }
    case 2:
        {
            SlotOnGetIrisConfig();
            break;
        }
    case 3:
        {
            SlotOnGetDenoiseConfig();
            break;
        }
    case 4:
        {
            SlotOnGetWhiteBalance();
            break;
        }
    case 5:
        {
            SlotOnGetCameraOthers();
            break;
        }
    default:
        break;
    }
}

void multi_ipnc_demo::SlotOnWBGainChanged( int val )
{
    if (ui.cbWhiteBalance->currentIndex() == 1)
    {
        ui.widgetGain->setVisible(true);
    }
    else
    {
        ui.widgetGain->setVisible(false);
    }
    ui.lblGainR->setText(QString::number(ui.hsldGainR->value()));
    ui.lblGainB->setText(QString::number(ui.hsldGainB->value()));
    if (val >= 0)
    {
        SlotOnSetWhiteBalance();
    }
}

void multi_ipnc_demo::SlotOnTabPageChanged( int index )
{
    QString tab_name = ui.tabConfigPage->currentWidget()->objectName();

    for (unsigned i = 0;i < motion_trigger_output_.size();++i)
    {
        if (i < device_details_.alarm_output)
        {
            (motion_trigger_output_.at(i))->setVisible(true);
            (portin_trigger_output_.at(i))->setVisible(true);
            (exp_trigger_output_.at(i))->setVisible(true);
        }
        else
        {
            (motion_trigger_output_.at(i))->setVisible(false);
            (portin_trigger_output_.at(i))->setVisible(false);
            (exp_trigger_output_.at(i))->setVisible(false);
        }
    }

    if (tab_name == "tabCamera")
    {
        if (ui.tbCameraConfig->currentIndex() != 0)
        {
            ui.tbCameraConfig->setCurrentIndex(0);
        }
        else
        {
            SlotOnGetCameraParams();
        }
    }
    else if (tab_name == "tabAlarmSchedule")
    {
        HandleAlarmScheduleType(0);
    }
    else if (tab_name == "tabPortAlarm")
    {
        RebuildPortChannel();
        SlotOnGetPortInput(0);
        SlotOnGetPortOutput(0);
        SlotOnGetException(0);
    }
    
    if (tab_name == "tabRecordSchedule")
    {
        HandleRecordScheduleType(0);
        SlotOnGetStoragePage();
    }
    else
    {
        CloseGetStoragePage();
    }
    
    if (tab_name == "tabMotionAlarm")
    {
        if (device_id_ >= 0)
        {
            NsstChannel nsst_channel;
            if (GetSelectedStreamInfo(&nsst_channel))
            {
                NSSTGetMotionAlarmArea(&nsst_channel);
                NSSTGetMotionAlarmConfig(&nsst_channel);
                NSSTGetAlarmTrigger(&nsst_channel,ATRIGGER_MOTION);
            }
        }
    }
    else
    {
        CloseAlarmGridDraw();
    }

    if (tab_name != "tabVAConfig")
    {
        CloseOSDDraw();
    }
}

void multi_ipnc_demo::SlotOnVDenoiseChanged( int val )
{
    ui.lbl2DLevel->setText(QString::number(ui.hsld2DLevel->value()));
    ui.lbl3DLevel->setText(QString::number(ui.hsld3DLevel->value()));
    if (device_id_ >= 0 && val >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetVideoDenoise(&nsst_channel,
                ui.cbVDenoiseEnable->currentIndex(),
                ui.hsld2DLevel->value(),
                ui.hsld3DLevel->value());
        }
    }
}

void multi_ipnc_demo::ShowCommonLog(NsstEventCommonParam* event_param,const QString& config_name)
{
    QString log;
    STATUS_LOG_LEVEL loglevel = STATUS_LOG_WARNING;
    if (event_param->result == NSST_SUCCESS)
    {
        if (event_param->get_or_set == NS_CMD_GET)
        {
            log.sprintf("Get %s success.",config_name.toUtf8().data());
        }
        else
        {
            log.sprintf("Set %s success.",config_name.toUtf8().data());
        }
    }
    else
    {
        loglevel = STATUS_LOG_ERROR;
        if (event_param->get_or_set == NS_CMD_GET)
        {
            log.sprintf("Get %s failed.",config_name.toUtf8().data());
        }
        else
        {
            log.sprintf("Set %s failed.",config_name.toUtf8().data());
        }
    }
    ShowStatus(loglevel,log);
}

void multi_ipnc_demo::SlotOnWDRChanged( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetWDR(&nsst_channel,ui.cbWDR->currentIndex(),ui.spinWDRLevel->value());
        }
    }
}

void multi_ipnc_demo::SlotOnMirrorChanged( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetVideoMirror(&nsst_channel,ui.cbMirrorEnable->currentIndex());
        }
    }
}

void multi_ipnc_demo::SlotOnVideoStandardChanged( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetVideoStandard(&nsst_channel,ui.cbVideoStandard->currentIndex());
        }
    }
}

void multi_ipnc_demo::SlotOnLocalOutputChanged( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetLocalOutput(&nsst_channel,ui.cbLocalOutput->currentIndex());
        }
    }
}

void multi_ipnc_demo::SlotOnDayNightChanged( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetDayNightSwitch(&nsst_channel,ui.cbDayNight->currentIndex(),ui.cbDayNightSens->currentIndex());
        }
    }
}

void multi_ipnc_demo::DoStartTalk()
{
    if (device_id_ >= 0)
    {
        NSSTStartTalk(device_id_);
    }
}

void multi_ipnc_demo::DoStopTalk()
{
    if (device_id_ >= 0)
    {
        NSSTStopTalk(device_id_);
    }
}

void multi_ipnc_demo::SlotOnGetAudioInput()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTGetAudioInput(&nsst_channel);
        }
    }
}

void multi_ipnc_demo::SlotOnSetAudioInput()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetAudioInput(&nsst_channel,
                ui.cbbAudioInput->itemData(ui.cbbAudioInput->currentIndex()).toInt(),
                ui.spinAudioInputVolume->value());
        }
    }
}

void multi_ipnc_demo::SlotOnStartSeq()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetPTZSequence(&nsst_channel,
                ui.cbbSequenceIndex->currentIndex(),
                NS_PTZ_SEQUENCE_START,NULL,0);
        }
    }
}

void multi_ipnc_demo::SlotOnStopSeq()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetPTZSequence(&nsst_channel,
                ui.cbbSequenceIndex->currentIndex(),
                NS_PTZ_SEQUENCE_STOP,NULL,0);
        }
    }
}

void multi_ipnc_demo::SlotOnSaveSeq()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            int count = ui.ltwSeqPresets->rowCount();
            if (count > 0)
            {
                NsstPTZSequenceItem* p = new NsstPTZSequenceItem[count];
                for (unsigned i = 0;i<count;++i)
                {
                    p[i].preset = ui.ltwSeqPresets->item(i,0)->text().toInt();
                    p[i].delay = ui.ltwSeqPresets->item(i,1)->text().toInt();
                    p[i].speed = ui.ltwSeqPresets->item(i,2)->text().toInt();
                }
                NSSTSetPTZSequence(&nsst_channel,
                    ui.cbbSequenceIndex->currentIndex(),
                    NS_PTZ_SEQUENCE_COVER,p,count);
                delete[] p;
            }
            else
            {
                NSSTSetPTZSequence(&nsst_channel,
                    ui.cbbSequenceIndex->currentIndex(),
                    NS_PTZ_SEQUENCE_COVER,NULL,0);
            }
        }
    }
}

void multi_ipnc_demo::SlotOnDelSeq()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTSetPTZSequence(&nsst_channel,
                ui.cbbSequenceIndex->currentIndex(),
                NS_PTZ_SEQUENCE_DELETE,NULL,0);
        }
    }
}

void multi_ipnc_demo::SlotOnClearSeq()
{
    ui.ltwSeqPresets->setRowCount(0);
}

void multi_ipnc_demo::SlotOnAddSeq()
{
    ui.ltwSeqPresets->setRowCount(ui.ltwSeqPresets->rowCount()+1);
    int row = ui.ltwSeqPresets->rowCount() - 1;
    ui.ltwSeqPresets->setItem(row,0,new QTableWidgetItem(QString::number(ui.cbbSeqPresets->currentIndex()+1)));
    ui.ltwSeqPresets->setItem(row,1,new QTableWidgetItem(QString::number(ui.spinSeqPresetDelay->value())));
    ui.ltwSeqPresets->setItem(row,2,new QTableWidgetItem(QString::number(ui.spinSeqPresetSpeed->value())));
}

void multi_ipnc_demo::SlotOnSeqListChanged( int index )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTGetPTZSequence(&nsst_channel,ui.cbbSequenceIndex->currentIndex());
        }
    }
}

void multi_ipnc_demo::SlotOnTboxPTZChanged( int index )
{
    if (index == 1)
    {
        if (ui.cbbSequenceIndex->currentIndex() != 0)
        {
            ui.cbbSequenceIndex->setCurrentIndex(0);
        }
        else
        {
            SlotOnSeqListChanged(0);
        }
    }
    else if (index == 3)
    {
        if (device_id_ >= 0)
        {
            NsstChannel nsst_channel;
            if (GetSelectedStreamInfo(&nsst_channel))
            {
                NSSTGetIRLed(&nsst_channel);
            }
        }
    }
}

void multi_ipnc_demo::SlotOnStartPattern()
{
    PTZPattern(NS_PTZ_PATTERN_START);
}

void multi_ipnc_demo::SlotOnStopPattern()
{
    PTZPattern(NS_PTZ_PATTERN_STOP);
}

void multi_ipnc_demo::SlotOnStartRecordPattern()
{
    PTZPattern(NS_PTZ_PATTERN_SET_START);
}

void multi_ipnc_demo::SlotOnStopRecordPattern()
{
    PTZPattern(NS_PTZ_PATTERN_SET_STOP);
}

void multi_ipnc_demo::PTZPattern( int control )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTPTZPattern(&nsst_channel,ui.cbbPatternIndex->currentIndex(),control);
        }
    }
}

void multi_ipnc_demo::SlotOnStartScan()
{
    PTZScan(NS_PTZ_SCAN_START);
}

void multi_ipnc_demo::SlotOnStopScan()
{
    PTZControl(NS_PTZ_MOVE_STOP);
}

void multi_ipnc_demo::SlotOnSetScanLeft()
{
    PTZScan(NS_PTZ_SCAN_SET_LEFT);
}

void multi_ipnc_demo::SlotOnSetScanRight()
{
    PTZScan(NS_PTZ_SCAN_SET_RIGHT);
}

void multi_ipnc_demo::SlotOnDeleteScan()
{
    PTZScan(NS_PTZ_SCAN_DELETE);
}

void multi_ipnc_demo::PTZScan( int control )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTPTZScan(&nsst_channel,
                ui.cbbScanIndex->currentIndex(),
                control,
                ui.hsldXSpeed->value());
        }
    }
}
void multi_ipnc_demo::SlotOnSetIRLed()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NsstIRConfig config;
            config.mode = ui.cbbIRStatus->currentIndex();
            config.auto_dimming = ui.cbbPowerAutoControl->currentIndex();
            config.illuminance = ui.cbbIRSensitivity->currentIndex()+1;
            config.near_compensation = ui.cbbIRCompensation->currentIndex();
            config.far_power = ui.cbbIRFar->currentIndex()+1;
            config.near_power = ui.cbbIRNear->currentIndex()+1;
            NSSTSetIRLed(&nsst_channel,&config);
        }
    }
}

void multi_ipnc_demo::SlotOnGetOSD()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NSSTGetOSD(&nsst_channel,NS_OSD_DATETIME);
            NSSTGetOSD(&nsst_channel,NS_OSD_CHANNEL_NAME);
            NSSTGetOSD(&nsst_channel,NS_OSD_TEXT);
        }
    }
}

void multi_ipnc_demo::SlotOnSetOSD()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            for (unsigned i = 0;i<3;++i)
            {
                RECT rc;
                NsstOSD config;
                memset(&config,0,sizeof(NsstOSD));
                if (video_widget_[0][0]->video_panel_label_->GetTextPosition(i,&rc))
                {
                    config.x = rc.left;
                    config.y = rc.top;
                }

                config.osd_type = (NS_OSD_TYPE)i;
                
                if (config.osd_type == NS_OSD_DATETIME)
                {
                    config.date_format = ui.cbOSDDateFormat->currentIndex();
                    config.time_format = ui.cbOSDTimeFormat->currentIndex();

                    config.enable = ui.cbDisplayDate->checkState() == Qt::Checked ? 1 : 0;
                }
                else if (config.osd_type == NS_OSD_CHANNEL_NAME)
                {
                    strncpy_s(config.text, sizeof(config.text), ui.edtChannelName->text().toUtf8().data(), _TRUNCATE);
                    config.enable = ui.cbDisplayName->checkState() == Qt::Checked ? 1 : 0;
                }
                else
                {
                    strncpy_s(config.text, sizeof(config.text), ui.textOSD->toPlainText().toUtf8().data(), _TRUNCATE);
                    config.enable = ui.cbDisplayOSD->checkState() == Qt::Checked ? 1 : 0;
                }
                
                NSSTSetOSD(&nsst_channel,&config);
            }
        }
    }
}

void multi_ipnc_demo::SlotOnVAPageChanged( int index )
{
    if (ui.tbVAConfig->currentIndex() != 2)
    {
        CloseOSDDraw();
    }
}

void multi_ipnc_demo::CloseOSDDraw()
{
    video_widget_[0][0]->StopDrawText(NS_OSD_TEXT);
    video_widget_[0][0]->StopDrawText(NS_OSD_CHANNEL_NAME);
    video_widget_[0][0]->StopDrawText(NS_OSD_DATETIME);
}

void multi_ipnc_demo::SlotOnGetDDNS()
{
    if (device_id_ >= 0)
    {
        NSSTGetDDNS(device_id_);
    }
}

void multi_ipnc_demo::SlotOnSetDDNS()
{
    if (device_id_ >= 0 && !ui.cbbDDNSAlias->currentText().isEmpty())
    {
        NsstDDNS ddns;
        strncpy_s(ddns.address,NSST_SHORT_LEN,ui.edtDDNSAddress->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(ddns.domain,NSST_SHORT_LEN,ui.edtDDNSDomain->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(ddns.alias,NSST_SHORT_LEN,ui.cbbDDNSAlias->currentText().toUtf8().data(),_TRUNCATE);
        strncpy_s(ddns.username,NSST_SHORT_LEN,ui.edtDDNSUser->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(ddns.password,NSST_SHORT_LEN,ui.edtDDNSPassword->text().toUtf8().data(),_TRUNCATE);
        ddns.port = ui.edtDDNSPort->text().toUInt();

        NSSTSetDDNS(device_id_,ui.cbDDNSEnable->checkState(),&ddns);
    }
}

void multi_ipnc_demo::SlotOnGetPPPoE()
{
    if (device_id_ >= 0)
    {
        NSSTGetPPPoE(device_id_);
    }
}

void multi_ipnc_demo::SlotOnSetPPPoE()
{
    if (device_id_ >= 0)
    {
        NsstPPPoE config;
        strncpy_s(config.username,NSST_SHORT_LEN,ui.edtPPPUserName->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.password,NSST_SHORT_LEN,ui.edtPPPPassword->text().toUtf8().data(),_TRUNCATE);
        config.enable = ui.cbPPPoEEnable->checkState();

        NSSTSetPPPoE(device_id_,&config);
    }
}

void multi_ipnc_demo::SlotOnGetFtp()
{
    if (device_id_ >= 0)
    {
        NSSTGetFTP(device_id_);
    }
}

void multi_ipnc_demo::SlotOnSetFtp()
{
    if (device_id_ >= 0)
    {
        NsstFTP config;
        strncpy_s(config.svr_address,NSST_SHORT_LEN,ui.edtFTPAddress->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.username,NSST_SHORT_LEN,ui.edtFTPUserName->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.password,NSST_SHORT_LEN,ui.edtFTPPassword->text().toUtf8().data(),_TRUNCATE);
        config.svr_port = ui.edtFTPPort->text().toUInt();
        config.dir_level_count = ui.cbFTPDir->currentIndex();
        config.dir_level_1 = ui.cbFTPParentDir->currentIndex();
        config.dir_level_2 = ui.cbFTPChildDir->currentIndex();
        NSSTSetFTP(device_id_,&config);
    }
}

void multi_ipnc_demo::SlotOnGetUPnP()
{
    if (device_id_ >= 0)
    {
        NSSTGetUPnP(device_id_);
    }
}

void multi_ipnc_demo::SlotOnSetUPnP()
{
    if (device_id_ >= 0)
    {
        NSSTSetUPnP(device_id_,ui.cbUPnPEnable->checkState(),ui.edtUPnPAlias->text().toUtf8().data());
    }
}

void multi_ipnc_demo::SlotOnGetPort()
{

}

void multi_ipnc_demo::SlotOnSetPort()
{

}

void multi_ipnc_demo::SlotOnGetEmail()
{
    if (device_id_ >= 0)
    {
        NSSTGetEmail(device_id_);
    }
}

void multi_ipnc_demo::SlotOnSetEmail()
{
    if (device_id_ >= 0)
    {
        NsstEmail config;
        strncpy_s(config.sender_name,NSST_SHORT_LEN,ui.edtEmailSName->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.sender_email,NSST_SHORT_LEN,ui.edtEmailSAddress->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.smtp_server,NSST_SHORT_LEN,ui.edtSMTPServer->text().toUtf8().data(),_TRUNCATE);
        config.smtp_port = ui.edtSMTPPort->text().toUInt();

        strncpy_s(config.username,NSST_SHORT_LEN,ui.edtEmailUserName->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.password,NSST_SHORT_LEN,ui.edtEmailPassword->text().toUtf8().data(),_TRUNCATE);

        strncpy_s(config.mailto_name[0],NSST_SHORT_LEN,ui.edtEmailRName0->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.mailto_email[0],NSST_SHORT_LEN,ui.edtEmailRAddress0->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.mailto_name[1],NSST_SHORT_LEN,ui.edtEmailRName1->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.mailto_email[1],NSST_SHORT_LEN,ui.edtEmailRAddress1->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.mailto_name[2],NSST_SHORT_LEN,ui.edtEmailRName2->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.mailto_email[2],NSST_SHORT_LEN,ui.edtEmailRAddress2->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.mailto_name[3],NSST_SHORT_LEN,ui.edtEmailRName3->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(config.mailto_email[3],NSST_SHORT_LEN,ui.edtEmailRAddress3->text().toUtf8().data(),_TRUNCATE);
        NSSTSetEmail(device_id_,&config);
    }
}

void multi_ipnc_demo::SlotOnDDNSAliasChanged( int index )
{
    if (ddnslist_)
    {
        ui.edtDDNSAddress->setText(ddnslist_[index].address);
        ui.edtDDNSDomain->setText(ddnslist_[index].domain);
        ui.edtDDNSPort->setText(QString::number(ddnslist_[index].port));
        ui.edtDDNSUser->setText(ddnslist_[index].username);
        ui.edtDDNSPassword->setText(ddnslist_[index].password);
    }
}

void multi_ipnc_demo::SlotOnFTPAnonyChanged(int state)
{
    if (ui.cbFTPAnonymous->checkState() == Qt::Checked)
    {
        ui.edtFTPUserName->setEnabled(false);
        ui.edtFTPUserName->setText("anonymous");
        ui.edtFTPPassword->setText("");
    }
    else
    {
        ui.edtFTPUserName->setEnabled(true);
        ui.edtFTPPassword->setEnabled(true);
    }
}

void multi_ipnc_demo::SlotSetUser()
{
    if (device_id_ >= 0)
    {
        NsstUserManage user;
        strncpy_s(user.old_name,NSST_SHORT_LEN,ui.edtUserName->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(user.new_name,NSST_SHORT_LEN,ui.edtNewName->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(user.password,NSST_SHORT_LEN,ui.edtUserNewPassword->text().toUtf8().data(),_TRUNCATE);
        user.level = ui.cbbUserLevel->currentIndex();
        NSSTSetUsers(device_id_,0,&user);
    }
}

void multi_ipnc_demo::SlotDeleteUser()
{
    if (device_id_ >= 0)
    {
        NsstUserManage user;
        strncpy_s(user.old_name,NSST_SHORT_LEN,ui.edtUserName->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(user.new_name,NSST_SHORT_LEN,ui.edtNewName->text().toUtf8().data(),_TRUNCATE);
        strncpy_s(user.password,NSST_SHORT_LEN,ui.edtUserNewPassword->text().toUtf8().data(),_TRUNCATE);
        user.level = ui.cbbUserLevel->currentIndex();
        NSSTSetUsers(device_id_,1,&user);
    }
}

void multi_ipnc_demo::SlotGetUsers()
{
    if (device_id_ >= 0)
    {
        NSSTGetUsers(device_id_);
    }
}

void multi_ipnc_demo::SlotClickUserList(int row, int column)
{
    if (row >= 0)
    {
        QTableWidgetItem * item = ui.ltwUsers->item(row,1);
        ui.edtUserName->setText(item->text());

        item = ui.ltwUsers->item(row,2);
        ui.cbbUserLevel->setCurrentIndex(item->text().toUInt());

        ui.edtNewName->setText("");
        ui.edtUserNewPassword->setText("");
    }
}

void multi_ipnc_demo::SlotOnGetAuth()
{
    if (device_id_ >= 0)
    {
        NSSTGetRTSPAuth(device_id_);
        NSSTGetAnonymous(device_id_);
    }
}

void multi_ipnc_demo::SlotOnSetAuth()
{
    if (device_id_ >= 0)
    {
        NSSTSetRTSPAuth(device_id_,ui.cbbRTSPAuth->currentIndex());
        NSSTSetAnonymous(device_id_,ui.cbbAnonymous->currentIndex());
    }
}

void multi_ipnc_demo::SlotOnGetIPFilter()
{
    if (device_id_ >= 0)
    {
        NSSTGetIPFilter(device_id_);
    }
}

void multi_ipnc_demo::SetIPFilter()
{
    if (device_id_ >= 0)
    {
        NsstIPFilter filter;
        memset(&filter,0,sizeof(filter));
        filter.count = ui.ltwIPFilterList->rowCount();
        filter.enable = ui.cbbIPFilter->checkState() ? 1 : 0;
        filter.mode = ui.cbbIPFilterMode->currentIndex();
        for (unsigned i = 0;i < filter.count;++i)
        {
            QTableWidgetItem* item = ui.ltwIPFilterList->item(i,1);
            strncpy_s(filter.list[i],NSST_SHORT_LEN,item->text().toUtf8().data(),_TRUNCATE);
        }
        NSSTSetIPFilter(device_id_,&filter);
    }
}

void multi_ipnc_demo::SlotOnDeleteIPFilter()
{
    if (ui.ltwIPFilterList->currentRow() >= 0)
    {
        ui.ltwIPFilterList->removeRow(ui.ltwIPFilterList->currentRow());
        for (unsigned i = 0;i < ui.ltwIPFilterList->rowCount();i++)
        {
            ui.ltwIPFilterList->setItem(i,0,new QTableWidgetItem(QString::number(i+1)));
        }
        SetIPFilter();
    }
}

void multi_ipnc_demo::SlotOnAddIPFilter()
{
    if (!ui.edtIPToAdd->text().isEmpty())
    {
        int row = ui.ltwIPFilterList->rowCount();
        ui.ltwIPFilterList->insertRow(row);
        ui.ltwIPFilterList->setItem(row,0,new QTableWidgetItem(QString::number(row+1)));
        ui.ltwIPFilterList->setItem(row,1,new QTableWidgetItem(ui.edtIPToAdd->text()));
        SetIPFilter();
    }
}

void multi_ipnc_demo::SlotOnClearMotionArea()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            video_widget_[nsst_channel.channel][nsst_channel.stream]->ClearDrawAlarmGrid();
        }
    }
}

void multi_ipnc_demo::SlotOnSaveMotionArea()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            int area[NSST_ALARM_AREA_VMAX];
            NSSTGetAllDrawAlarmArea(&nsst_channel,area);
            NSSTSetMotionAlarmArea(&nsst_channel,area);
            NSSTSetMotionAlarmConfig(&nsst_channel,
                QT_CHECK_STATE2BOOL(ui.cbbMotionEnable->checkState()),
                ui.spinMotionSensitivity->value());
        }
    }
}

void multi_ipnc_demo::CloseAlarmGridDraw()
{
    for (unsigned i = 0;i < MAX_CHANNEL;++i)
    {
        for (unsigned j = 0;j < MAX_STREAM_PER_CHANNEL;++j)
        {
            video_widget_[i][j]->StopDrawAlarmGrid();
        }
    }
}

void multi_ipnc_demo::HandleAlarmTrigger( NsstAlarmTrigger* trigger,int channel )
{
    switch (trigger->alarm_type)
    {
    case ATRIGGER_MOTION:
        HandleMotionTrigger(trigger,channel);
    	break;
    case ATRIGGER_MASK:
        HandleMaskTrigger(trigger,channel);
        break;
    case ATRIGGER_PORT:
        HandlePortInputTrigger(trigger,channel);
        break;
    case ATRIGGER_DISK_FULL:
    case ATRIGGER_DISK_ERROR:
    case ATRIGGER_NET_DISCONNECTED:
    case ATRIGGER_IP_CONFLICT:
        HandleExceptionTrigger(trigger,channel);
        break;
    default:
        break;
    }
}

void multi_ipnc_demo::HandleMotionTrigger( NsstAlarmTrigger* trigger,int channel )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel)
            && nsst_channel.channel == channel)
        {
            ui.cbMotionTriggerAudio->setCheckState(QT_CHECK_STATE(trigger->audio));
            ui.cbMotionTriggerCenter->setCheckState(QT_CHECK_STATE(trigger->broadcast));
            ui.cbMotionTriggerRecord->setCheckState(QT_CHECK_STATE(trigger->record));
            ui.cbMotionTriggerSnapshot->setCheckState(QT_CHECK_STATE(trigger->snapshot));
            ui.cbMotionTriggerFtp->setCheckState(QT_CHECK_STATE(trigger->snapshot_ftp));
            ui.cbMotionTriggerEmail->setCheckState(QT_CHECK_STATE(trigger->snapshot_email));
            ui.cbMotionTriggerSD->setCheckState(QT_CHECK_STATE(trigger->snapshot_sdcard));

            for (unsigned i = 0;i < motion_trigger_output_.size();++i)
            {
                (motion_trigger_output_.at(i))->setCheckState(QT_CHECK_STATE(getbit(trigger->port,i)));
            }
        }
    }
}

void multi_ipnc_demo::HandleMaskTrigger( NsstAlarmTrigger* trigger,int channel )
{

}

void multi_ipnc_demo::HandlePortInputTrigger( NsstAlarmTrigger* trigger,int channel )
{
    if (channel == ui.cbbPortInNum->currentIndex())
    {
        ui.cbPortInTriggerCenter->setCheckState(QT_CHECK_STATE(trigger->broadcast));
        ui.cbPortInTriggerRecord->setCheckState(QT_CHECK_STATE(trigger->record));
        ui.cbPortInTriggerSnapshot->setCheckState(QT_CHECK_STATE(trigger->snapshot));
        ui.cbPortInTriggerFtp->setCheckState(QT_CHECK_STATE(trigger->snapshot_ftp));
        ui.cbPortInTriggerEmail->setCheckState(QT_CHECK_STATE(trigger->snapshot_email));
        ui.cbPortInTriggerSD->setCheckState(QT_CHECK_STATE(trigger->snapshot_sdcard));

        for (unsigned i = 0;i < portin_trigger_output_.size();++i)
        {
            (portin_trigger_output_.at(i))->setCheckState(QT_CHECK_STATE(getbit(trigger->port,i)));
        }

        if (trigger->ptz_preset > 0)
        {
            ui.rbPortTriggerPreset->setChecked(true);
            ui.cbbPortInPreset->setCurrentIndex(trigger->ptz_preset-1);
        }
        else if (trigger->ptz_sequence >= 0)
        {
            ui.rbPortTriggerSeq->setChecked(true);
            ui.cbbPortInSequance->setCurrentIndex(trigger->ptz_sequence);
        }
        else if (trigger->ptz_scan >= 0)
        {
            ui.rbPortTriggerScan->setChecked(true);
            ui.cbbPortInScan->setCurrentIndex(trigger->ptz_scan);
        }
        else
        {
            ui.rbPortTriggerPTZ->setChecked(true);
        }
    }
}

void multi_ipnc_demo::HandleExceptionTrigger( NsstAlarmTrigger* trigger,int channel )
{
    if (trigger->alarm_type == ui.cbbExpType->currentIndex() + ATRIGGER_DISK_FULL)
    {
        ui.cbExpTriggerCenter->setCheckState(QT_CHECK_STATE(trigger->broadcast));
        ui.cbExpTriggerSnapshot->setCheckState(QT_CHECK_STATE(trigger->snapshot));
        ui.cbExpTriggerFtp->setCheckState(QT_CHECK_STATE(trigger->snapshot_ftp));
        ui.cbExpTriggerEmail->setCheckState(QT_CHECK_STATE(trigger->snapshot_email));
        ui.cbExpTriggerSD->setCheckState(QT_CHECK_STATE(trigger->snapshot_sdcard));

        for (unsigned i = 0;i < exp_trigger_output_.size();++i)
        {
            (exp_trigger_output_.at(i))->setCheckState(QT_CHECK_STATE(getbit(trigger->port,i)));
        }
    }
}

void multi_ipnc_demo::SlotSaveMotionTrigger()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        if (GetSelectedStreamInfo(&nsst_channel))
        {
            NsstAlarmTrigger trigger;
            memset(&trigger,0,sizeof(NsstAlarmTrigger));
            trigger.alarm_type = ATRIGGER_MOTION;
            trigger.audio = QT_CHECK_STATE2BOOL_EX(cbMotionTriggerAudio);
            trigger.broadcast = QT_CHECK_STATE2BOOL_EX(cbMotionTriggerCenter);
            trigger.record = QT_CHECK_STATE2BOOL_EX(cbMotionTriggerRecord);
            trigger.snapshot = QT_CHECK_STATE2BOOL_EX(cbMotionTriggerSnapshot);
            trigger.snapshot_ftp = QT_CHECK_STATE2BOOL_EX(cbMotionTriggerFtp);
            trigger.snapshot_email = QT_CHECK_STATE2BOOL_EX(cbMotionTriggerEmail);
            trigger.snapshot_sdcard = QT_CHECK_STATE2BOOL_EX(cbMotionTriggerSD);
            //setbit(trigger.port);
            for (unsigned i = 0;i < motion_trigger_output_.size();++i)
            {
                if (i < device_details_.alarm_output)
                {
                    if ((motion_trigger_output_.at(i))->checkState() == Qt::Checked)
                    {
                        setbit(trigger.port,i);
                    }   
                }
            }
            NSSTSetAlarmTrigger(&nsst_channel,&trigger);
        }
    }
}

void multi_ipnc_demo::HandleAlarmSchedule(int val)
{
    int sel_day = ui.cbbScheduleDay->currentIndex();
    for (unsigned i = 0;i < 7;++i)
    {
        if (i == sel_day)
        {
            (schedule_copy_.at(i))->setCheckState(Qt::Checked);
            (schedule_copy_.at(i))->setEnabled(false);
        }
        else
        {
            (schedule_copy_.at(i))->setCheckState(Qt::Unchecked);
            (schedule_copy_.at(i))->setEnabled(true);
        }
    }
    
    NsstAlarmSchedule* p = &alarm_schedule_[ui.cbbScheduleType->currentIndex()];
    for (unsigned i = 0;i < NS_MAX_TIME_SEG;++i)
    {
        QTime start(0,0),end(0,0);
        int starttime = p->dayofweek[sel_day].start[i];
        int endtime = p->dayofweek[sel_day].end[i];

        if (DAY_SECONDS == starttime)
        {
            starttime = DAY_SECONDS - 1;
        }
        if (DAY_SECONDS == endtime)
        {
            endtime = DAY_SECONDS - 1;
        }

        (schedule_start_.at(i))->setTime(start.addSecs(starttime));
        (schedule_end_.at(i))->setTime(end.addSecs(endtime));
    }
}

void multi_ipnc_demo::HandleAlarmScheduleType( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = ui.cbbScheduleChannel->currentIndex();

        int type = ui.cbbScheduleType->currentIndex();
        NSSTGetAlarmSchedule(&nsst_channel,(NS_ALARM_TYPE)type);
        memset(&alarm_schedule_[type],0,sizeof(NsstAlarmSchedule));
    }
}

void multi_ipnc_demo::SlotOnSaveSchedule()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = ui.cbbScheduleChannel->currentIndex();

        QTime zero(24,0);
        int type = ui.cbbScheduleType->currentIndex();
        int sel_day = ui.cbbScheduleDay->currentIndex();

        NsstAlarmSchedule schedule;
        memcpy(&schedule,&alarm_schedule_[type],sizeof(NsstAlarmSchedule));

         for (unsigned i = 0;i < 7;++i)
         {
             if ((schedule_copy_.at(i))->checkState() == Qt::Checked)
             {
                 for (unsigned j = 0;j < NS_MAX_TIME_SEG;++j)
                 {
                     schedule.dayofweek[i].start[j] = abs((schedule_start_.at(j))->time().secsTo(zero));
                     schedule.dayofweek[i].end[j] = abs((schedule_end_.at(j))->time().secsTo(zero));
                 }
             }
         }
         NSSTSetAlarmSchedule(&nsst_channel,&schedule);
    }
}

void multi_ipnc_demo::SlotOnReboot()
{
    if (device_id_ >= 0)
    {
        NSSTRebootDevice(device_id_);
    }
}

void multi_ipnc_demo::SlotOnSimpleRestore()
{
    if (device_id_ >= 0)
    {
        NSSTRestoreDevice(device_id_,1);
    }
}

void multi_ipnc_demo::SlotOnCompleteRestore()
{
    if (device_id_ >= 0)
    {
        NSSTRestoreDevice(device_id_,0);
    }
}

void multi_ipnc_demo::SlotOnGetPortInput( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = ui.cbbPortInNum->currentIndex();
        NSSTGetPortAlarm(&nsst_channel,0);
        NSSTGetAlarmTrigger(&nsst_channel,ATRIGGER_PORT);
    }
}

void multi_ipnc_demo::SlotOnGetPortOutput( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = ui.cbbPortOutNum->currentIndex();
        NSSTGetPortAlarm(&nsst_channel,1);
        NSSTGetOutputDelay(&nsst_channel);
    }
}

void multi_ipnc_demo::SlotOnGetException( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = 0;

        NSSTGetAlarmTrigger(&nsst_channel,(NS_TRIGGER_ATYPE)(ui.cbbExpType->currentIndex() + ATRIGGER_DISK_FULL));
    }
}

void multi_ipnc_demo::SlotSavePortInput()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = ui.cbbPortInNum->currentIndex();

        NsstAlarmTrigger trigger;
        memset(&trigger,0,sizeof(NsstAlarmTrigger));
        trigger.alarm_type = ATRIGGER_PORT;
        trigger.audio = -1;
        trigger.broadcast = QT_CHECK_STATE2BOOL_EX(cbPortInTriggerCenter);
        trigger.record = QT_CHECK_STATE2BOOL_EX(cbPortInTriggerRecord);
        trigger.snapshot = QT_CHECK_STATE2BOOL_EX(cbPortInTriggerSnapshot);
        trigger.snapshot_ftp = QT_CHECK_STATE2BOOL_EX(cbPortInTriggerFtp);
        trigger.snapshot_email = QT_CHECK_STATE2BOOL_EX(cbPortInTriggerEmail);
        trigger.snapshot_sdcard = QT_CHECK_STATE2BOOL_EX(cbPortInTriggerSD);

        trigger.ptz_preset = ui.rbPortTriggerPreset->isChecked() ? ui.cbbPortInPreset->currentIndex() + 1 : -1;
        trigger.ptz_sequence = ui.rbPortTriggerSeq->isChecked() ? ui.cbbPortInSequance->currentIndex() : -1;
        trigger.ptz_scan = ui.rbPortTriggerScan->isChecked() ? ui.cbbPortInScan->currentIndex() : -1;

        for (unsigned i = 0;i < portin_trigger_output_.size();++i)
        {
            if (i < device_details_.alarm_output)
            {
                if ((portin_trigger_output_.at(i))->checkState() == Qt::Checked)
                {
                    setbit(trigger.port,i);
                }   
            }
        }
        NSSTSetAlarmTrigger(&nsst_channel,&trigger);

        NsstPortAlarm config;
        config.enable = QT_CHECK_STATE2BOOL_EX(cbPortInputEnable);
        config.status = ui.cbbPortInStatus->currentIndex();
        config.type = 0;
        strncpy_s(config.title,NSST_SHORT_LEN,ui.PortInName->text().toUtf8().data(),_TRUNCATE);
        NSSTSetPortAlarm(&nsst_channel,&config);
    }
}

void multi_ipnc_demo::SlotSavePortOutput()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = ui.cbbPortOutNum->currentIndex();

        NsstPortAlarm config;
        config.status = ui.cbbPortOutStatus->currentIndex();
        config.type = 1;
        strncpy_s(config.title,NSST_SHORT_LEN,ui.PortOutName->text().toUtf8().data(),_TRUNCATE);
        NSSTSetPortAlarm(&nsst_channel,&config);

        NSSTSetOutputDelay(&nsst_channel,ui.spinOutputDelay->value());
    }
}

void multi_ipnc_demo::SlotSaveException()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = 0;

        NsstAlarmTrigger trigger;
        memset(&trigger,0,sizeof(NsstAlarmTrigger));
        trigger.alarm_type = (NS_TRIGGER_ATYPE)(ui.cbbExpType->currentIndex() + ATRIGGER_DISK_FULL);
        trigger.audio = -1;
        trigger.broadcast = QT_CHECK_STATE2BOOL_EX(cbExpTriggerCenter);
        trigger.record = -1;
        trigger.snapshot = QT_CHECK_STATE2BOOL_EX(cbExpTriggerSnapshot);
        trigger.snapshot_ftp = QT_CHECK_STATE2BOOL_EX(cbExpTriggerFtp);
        trigger.snapshot_email = QT_CHECK_STATE2BOOL_EX(cbExpTriggerEmail);
        trigger.snapshot_sdcard = QT_CHECK_STATE2BOOL_EX(cbExpTriggerSD);

        for (unsigned i = 0;i < exp_trigger_output_.size();++i)
        {
            if (i < device_details_.alarm_output)
            {
                if ((exp_trigger_output_.at(i))->checkState() == Qt::Checked)
                {
                    setbit(trigger.port,i);
                }   
            }
        }
        NSSTSetAlarmTrigger(&nsst_channel,&trigger);
    }
}

void multi_ipnc_demo::RebuildPortChannel()
{
    if (device_id_ >= 0)
    {
        if (device_details_.alarm_input > 0)
        {
            ui.cbbPortInNum->clear();
            for (unsigned i = 0;i < device_details_.alarm_input;++i)
            {
                ui.cbbPortInNum->addItem(QString::number(i));
            }
        }

        if (device_details_.alarm_output > 0)
        {
            ui.cbbPortOutNum->clear();
            for (unsigned i = 0;i < device_details_.alarm_output;++i)
            {
                ui.cbbPortOutNum->addItem(QString::number(i));
            }
        }
    }
}

void multi_ipnc_demo::SlotOnSaveRecSchedule()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = 0/*ui.cbbScheduleChannel->currentIndex()*/;

        QTime zero(24,0);
        int sel_day = ui.cbbRecScheduleDay->currentIndex();

        NsstRecordSchedule schedule;
        memcpy(&schedule,&record_schedule_,sizeof(NsstRecordSchedule));

        for (unsigned i = 0;i < 7;++i)
        {
            if ((schedule_copy_.at(i))->checkState() == Qt::Checked)
            {
                for (unsigned j = 0;j < NS_MAX_TIME_SEG;++j)
                {
                    schedule.dayofweek[i].start[j] = abs((rec_schedule_start_.at(j))->time().secsTo(zero));
                    schedule.dayofweek[i].end[j] = abs((rec_schedule_end_.at(j))->time().secsTo(zero));
                    schedule.record_type[i][j] = (NS_RECORD_TYPE)(rec_type_group_.at(j))->currentIndex();
                }
            }
        }
        NSSTSetRecordSchedule(&nsst_channel,&schedule);
    }
}

void multi_ipnc_demo::HandleRecordSchedule( int val )
{
    int sel_day = ui.cbbRecScheduleDay->currentIndex();
    for (unsigned i = 0;i < 7;++i)
    {
        if (i == sel_day)
        {
            (rec_schedule_copy_.at(i))->setCheckState(Qt::Checked);
            (rec_schedule_copy_.at(i))->setEnabled(false);
        }
        else
        {
            (rec_schedule_copy_.at(i))->setCheckState(Qt::Unchecked);
            (rec_schedule_copy_.at(i))->setEnabled(true);
        }
    }

    NsstRecordSchedule* p = &record_schedule_;
    for (unsigned i = 0;i < NS_MAX_TIME_SEG;++i)
    {
        QTime start(0,0),end(0,0);
        int starttime = p->dayofweek[sel_day].start[i];
        int endtime = p->dayofweek[sel_day].end[i];

        if (DAY_SECONDS == starttime)
        {
            starttime = DAY_SECONDS - 1;
        }
        if (DAY_SECONDS == endtime)
        {
            endtime = DAY_SECONDS - 1;
        }

        (rec_schedule_start_.at(i))->setTime(start.addSecs(starttime));
        (rec_schedule_end_.at(i))->setTime(end.addSecs(endtime));
        (rec_type_group_.at(i))->setCurrentIndex(p->record_type[sel_day][i]);
    }

    ui.cbRecSchedule->setCheckState(QT_CHECK_STATE(p->enable));
}

void multi_ipnc_demo::HandleRecordScheduleType( int val )
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = 0/*ui.cbbScheduleChannel->currentIndex()*/;

        NSSTGetRecordSchedule(&nsst_channel);
        memset(&record_schedule_,0,sizeof(NsstRecordSchedule));
    }
}

void multi_ipnc_demo::SlotOnGetStoragePage()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = 0;

        NSSTGetStorageQuota(&nsst_channel);
        TimerGetStorageDevices();
        NSSTGetCaptureConfig(&nsst_channel);
    }
}

void multi_ipnc_demo::SlotOnSaveQuota()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = 0;

        NSSTSetStorageQuota(&nsst_channel,ui.spinRecordQuota->value());
    }
}

void multi_ipnc_demo::SlotOnFormatDevices()
{
    if (device_id_ >= 0)
    {
        NSSTFormatStorageDevice(device_id_,ui.spinFormatIndex->value());
    }
}

void multi_ipnc_demo::CloseGetStoragePage()
{
    timer_get_storage_devices_->stop();
}

void multi_ipnc_demo::TimerGetStorageDevices()
{
    if (device_id_ >= 0)
    {
        NSSTGetStorageDevices(device_id_);
    }
}

void multi_ipnc_demo::SlotOnCaptureQuotaChanged( int val )
{
    ui.spinRecordQuota->setValue(100 - val);
}

void multi_ipnc_demo::SlotOnSaveCaptureConfig()
{
    if (device_id_ >= 0)
    {
        NsstChannel nsst_channel;
        nsst_channel.dev_id = device_id_;
        nsst_channel.channel = 0;

        NsstCaptureConfig config;
        config.enable = QT_CHECK_STATE2BOOL_EX(cbEnableSchCapture);
        config.format = 0;
        config.quality = ui.cbbCaptureQuality->currentIndex();
        config.interval_unit = ui.cbbCaptureUnit->currentIndex();
        config.interval_value = ui.spinCaptureInterval->value();
        config.trigger_ftp = QT_CHECK_STATE2BOOL_EX(cbCapToFTP);
        config.trigger_email = QT_CHECK_STATE2BOOL_EX(cbCapToEmail);
        config.trigger_sdcard = QT_CHECK_STATE2BOOL_EX(cbCapToSD);
        NSSTSetCaptureConfig(&nsst_channel,&config);
    }
}

void multi_ipnc_demo::SlotOnSetEZoom()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        RECT rc;
        rc.left = ui.spinEZoomX->value();
        rc.top = ui.spinEZoomY->value();
        rc.right = rc.left + ui.spinEZoomWidth->value();
        rc.bottom = rc.top + ui.spinEZoomHeight->value();
        NSSTMediaZoom(&nsst_channel,&rc);
    }
}

void multi_ipnc_demo::SlotOnResetEZoom()
{
    NsstChannel nsst_channel;
    if (GetSelectedStreamInfo(&nsst_channel))
    {
        NSSTMediaZoom(&nsst_channel,NULL);
    }
}

void multi_ipnc_demo::OnUpgradeClick()
{

}

void multi_ipnc_demo::OnTestMediaClick()
{
    int interval_seconds = AppSettingsInstance()->GetTestInterval();
    timer_test_media_->start(interval_seconds * 1000);
    OnTimerTestMedia();
}

void multi_ipnc_demo::OnStopTestMediaClick()
{
    timer_test_media_->stop();
}

void multi_ipnc_demo::OnTimerTestMedia()
{
    DoConnectAll();
}
