#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QThread>
#include <QTimer>
#include<string>
#include<dirent.h>
#include<unistd.h>
#include <thread>
#include <future>
#include <chrono>
#include <sstream>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <map>

#define gettid() syscall(SYS_gettid)

using namespace std;

V4l2DeviceInfo device_info;
KylinCameraInfo camera_info;
QTimer *pTimer = nullptr;
QTimer *cTimer = nullptr;
int itmp;
int ctr_id;
int video_enable = 0;

void printf_time_now(const QString &strFun , const QString &strArgs)
{
  char bufferTime[80];
  struct tm newtime;
  time_t now = time(0);
  localtime_r(&now , &newtime );
  strftime(bufferTime, sizeof(bufferTime), "%Y-%m-%d %H:%M:%S", &newtime);
  printf("**%s[%u]: timenow=%s msg=%s\n" , strFun.toStdString().c_str(),(unsigned int )gettid()  , bufferTime , strArgs.toStdString().c_str());

}


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->recordStartButton->setStyleSheet("background-color: rgb(0,200,0)");;
    ui->recordStopButton->setStyleSheet("background-color: rgb(200,0,0)"); ;
    ui->recordStopButton->hide();
    ui->checkBox->setChecked(true);

    this->installEventFilter(this);

    camera = new KylinCamera(this);
    KylinCamera::camera_log_init(LOG_DEBUG);

    //get device index    
    char dev_name[8];
    if(Get_DevIndex(dev_name , sizeof(dev_name))!=0)
        return;

    //show the index
    ui->comboBox_3->setCurrentText(dev_name);
    char in_devname[16] = "/dev/";
    //strcat(in_devname,dev_name);
    strncat(in_devname , dev_name , sizeof(in_devname)-strnlen(in_devname,sizeof(in_devname))-1);
    
    Enum_Device(in_devname , strnlen(in_devname , sizeof(in_devname)));    //枚举摄像头信息

    int iLen = strnlen(in_devname, sizeof(in_devname));
    if (iLen < sizeof(in_devname)) iLen = iLen +1;
    memcpy(camera_info.devname, in_devname, iLen);          //要打开的摄像头名称


    videoDisplay = camera->create(this, &camera_info);
    if(videoDisplay==NULL)
    {
        delete camera;
        camera = NULL;
        qDebug()<<"delete camera";
        readoutHandle();
    }



    /*
    QAudioDeviceInfo deviceInfo = QAudioDeviceInfo::defaultInputDevice();
    qDebug()<<"audio device:"<<deviceInfo.deviceName();
    camera->camera_audio_init(deviceInfo);
    */

    //init audio
    /*
    for( QAudioDeviceInfo &deviceInfo: QAudioDeviceInfo::availableDevices(QAudio::AudioInput))
    {
        if(deviceInfo.deviceName().contains("default"))
        {
            qDebug()<<"audio device:"<<deviceInfo.deviceName();
            camera->camera_audio_init(deviceInfo);
            break;
        }
        else
        {
             qDebug()<<deviceInfo.deviceName();
        }

    }
    */



    videoDisplay->setWindowFlags(Qt::CustomizeWindowHint|Qt::FramelessWindowHint);
    //ui->verticalLayout->addWidget(videoDisplay);
    ui->horizontalLayout_3->addWidget(videoDisplay);

    camera->camera_set_background(QColor(50,0,80));    //背景颜色

    camera->camera_display_mirror(true);    //镜像

    Current_Paramt();       //获取当前摄像头参数

    //set camera control
    Show_CtrlInfo();

    Dbus_Init();

    //错误信号
    connect(videoDisplay,SIGNAL(readout()),this, SLOT(readoutHandle()));
    //拍照错误信号
    connect(camera, SIGNAL(camera_photo_error()), this, SLOT(photoError()));

    connect(ui->restoreButton, SIGNAL(clicked()), this, SLOT(clickRestore()));
    connect(ui->resumeButton, SIGNAL(clicked()), this, SLOT(clickPause()));
    connect(ui->setButton, SIGNAL(clicked()), this, SLOT(clickSet()));
    connect(ui->set1Button, SIGNAL(clicked()), this, SLOT(clickSet1()));
    connect(ui->photoButton, SIGNAL(clicked()), this, SLOT(clickPhoto()));
    connect(ui->recordStartButton, SIGNAL(clicked()), this, SLOT(clickStartRecord()));
    connect(ui->recordStopButton, SIGNAL(clicked()), this, SLOT(clickStopRecord()));
    connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(clickCloseCamera()));
    connect(ui->startButton, SIGNAL(clicked()), this, SLOT(clickStartCamera()));
    connect(ui->videoEnableButton, SIGNAL(clicked()), this, SLOT(clickVideoEnable()));
    connect(ui->audioEnableButton, SIGNAL(clicked()), this, SLOT(clickAudioEnable()));
    connect(ui->displayMirrorButton, SIGNAL(clicked()), this, SLOT(clickDisplayMirror()));

    //dbus connect
    connect(m_dbus, &login1dbusManager::locking, this, &MainWindow::lockingHandle);

}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::InputMethod || event->type() == QEvent::KeyPress) {
        // 阻止事件传播
        return true;
    } else {
        // 标准事件处理
        return QObject::eventFilter(watched, event);
    }
}


int MainWindow::Get_DevIndex(char *dev_name, int devNameLen)
{
    DIR *dir;
    struct dirent *dirp;

    dir = opendir("/dev/");
    if(dir == NULL)
    {
        qDebug()<<"can not find dir";
        return -1;
    }

    //清除所以index
    ui->comboBox_3->clear();


    map<int , int> mCameraNum;
    int i = 0;
    while( (dirp = readdir(dir) ) != NULL)
    {
        char str[8] = {0};
        int iCamNum = 0;
        if(strstr(dirp->d_name,"video") != NULL)
        {
            sscanf(dirp->d_name,"%*[^0-9]%[0-9]",str);
            iCamNum = atoi(str);
            mCameraNum.insert(make_pair(iCamNum,iCamNum));
            ui->comboBox_3->addItem(dirp->d_name);
            qDebug()<<"d_name:"<<dirp->d_name<<",str:"<<str<<",camera_num:"<<iCamNum;
            i++;
        }
    }

    int tmp = 0;
    if (mCameraNum.size())
        tmp=mCameraNum[0];

    qDebug()<<"tmp="<<tmp;
    snprintf(dev_name ,devNameLen,"video%d",tmp);

    closedir(dir);

    return 0;
}

void MainWindow::Enum_Device(char *in_devname , int in_devNameLen)
{
    memset(&device_info,0,sizeof(device_info));
    memset(&camera_info,0,sizeof(camera_info));
    memcpy(device_info.dev_path, in_devname, in_devNameLen);     //设备名
    KylinCamera::enum_device(&device_info);                             //获取摄像头支持的参数

    //清除所以index
    ui->comboBox->clear();

    //参数解析和选择
    qDebug()<<"********************************************************";
    int i,j,k;
    //摄像头像素格式
    for(i=0;i<10;i++){
        TypePixFormats *pixfmt = &device_info.fmt_supported[i];
        unsigned int format = pixfmt->fmt.pixelformat;
        char formatArray[] = { (char)(format&0xff), (char)((format>>8)&0xff),
                               (char)((format>>16)&0xff), (char)((format>>24)&0xff), 0 };
        qDebug() << "pixel format: " << formatArray;
        if( strcmp(formatArray,"MJPG") == 0 ) {
            camera_info.format = V4L2_PIX_FMT_MJPEG;
            itmp = i;
            break;
        }
        if( strcmp(formatArray,"YUYV") == 0 ) {
            camera_info.format = V4L2_PIX_FMT_YUYV;
            itmp = i;
        }
    }

    //分辨率和帧率
    TypePixFormats *pixfmt = &device_info.fmt_supported[itmp];
    int first_flag = 1;
    for(j = 0; j < 50; j++) {
        TypeFramesizes *fsize = &pixfmt->frm_sizes[j];
        if(fsize->frm_size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
            pixfmt->frm_sizes_len++;
            //qDebug() << "{ discrete: width = "<< fsize->frm_size.discrete.width
                          //<< ", height = " << fsize->frm_size.discrete.height << "}";
            QString string_num = QString::number(fsize->frm_size.discrete.width) + "x" + QString::number(fsize->frm_size.discrete.height);
            ui->comboBox->addItem(string_num);          //展示当前参数

            for(k = 0; k < 10; k++) {
                struct v4l2_frmivalenum *fivals = &fsize->frm_ivals[k];
                if (fivals->type == V4L2_FRMIVAL_TYPE_DISCRETE) {
                    //qDebug() << fivals->discrete.numerator << "/" << fivals->discrete.denominator;
                    if(first_flag) {
                        first_flag = 0;
                        camera_info.width = fsize->frm_size.discrete.width;
                        camera_info.height = fsize->frm_size.discrete.height;
                        camera_info.fps = fivals->discrete.denominator;
                    }
                }
            }

        }
    }
    qDebug()<<"********************************************************";
}

void MainWindow::Current_Paramt()
{
    QString string_info;
    string_info += camera_info.devname;
    string_info += ":";


    KylinCameraInfo get_camera_info;
    camera->camera_get_param(&get_camera_info);


    char formatArray[] = { (char)(get_camera_info.format&0xff), (char)((get_camera_info.format>>8)&0xff),
                           (char)((get_camera_info.format>>16)&0xff), (char)((get_camera_info.format>>24)&0xff), 0 };
    string_info += ( formatArray +
            QString::number(get_camera_info.width) + "x" + QString::number(get_camera_info.height) + "," +
            QString::number(get_camera_info.fps) );



    ui->lineEdit->setText(string_info);



}

void MainWindow::Show_CtrlInfo()
{
    //set camera control
    QString string1 = "WHITE_BALANCE";
    QString string2 = "BRIGHTNESS";
    QString string3 = "CONTRAST";
    QString string4 = "SATURATION";
    QString string5 = "HUE";
    QString string6 = "SHARPNESS";
    QString string7 = "BACKL_COMP";
    QString string8 = "EXPOSURE_AUTO";
    QString string9 = "EXPOSURE_ABSOLUTE";

    ui->comboBox_2->addItem(string1);
    ui->comboBox_2->addItem(string2);
    ui->comboBox_2->addItem(string3);
    ui->comboBox_2->addItem(string4);
    ui->comboBox_2->addItem(string5);
    ui->comboBox_2->addItem(string6);
    ui->comboBox_2->addItem(string7);
    ui->comboBox_2->addItem(string8);
    ui->comboBox_2->addItem(string9);

    ctr_id = WHITE_BALANCE;
    struct v4l2_queryctrl argp;
    camera->camera_query_contrl(ctr_id, &argp);
    //qDebug()<<"maximum:"<<argp.maximum<<",minimum:"<<argp.minimum;
    ui->horizontalSlider->setMaximum(argp.maximum);
    //ui->horizontalSlider->setMinimum(argp.minimum);
}

void MainWindow::Dbus_Init()
{
    m_dbus = new login1dbusManager();
    //5. 准备在录像期间监听系统锁屏、睡眠信号
    m_dbus->inhibit(login1dbusManager::INHIBIT_SHUTDOWN);
    m_dbus->inhibit(login1dbusManager::INHIBIT_SLEEP);
}

void MainWindow::clickPause()
{
    camera->camera_capture_pause();
}

void MainWindow::clickRestore()
{
    camera->camera_capture_restore();
}

void MainWindow::clickSet()
{
    const char *in_devname = "/dev/video4";
    KylinCameraInfo camera_info;
    int iLen = strnlen(in_devname, sizeof(in_devname));
    if (iLen < sizeof(in_devname)) iLen = iLen + 1;
    memcpy(camera_info.devname, in_devname, iLen);
    camera_info.format = V4L2_PIX_FMT_MJPEG;
    camera_info.width = 800;
    camera_info.height = 600;
    camera_info.fps = 30;

    camera->camera_set_param(&camera_info);
}

void MainWindow::clickSet1()
{
    const char *in_devname = "/dev/video4";
    KylinCameraInfo camera_info;
    int iLen = strnlen(in_devname, sizeof(in_devname));
    if (iLen < sizeof(in_devname)) iLen = iLen + 1;
    memcpy(camera_info.devname, in_devname, iLen);
    camera_info.format = V4L2_PIX_FMT_MJPEG;
    camera_info.width = 1280;
    camera_info.height = 720;
    camera_info.fps = 30;

    camera->camera_set_param(&camera_info);
}

void MainWindow::photoError()
{
    qDebug()<< "photo error";
}

void MainWindow::clickPhoto()
{
    char name[30] = "kylin.jpg";

    camera->camera_take_photo(name );
    camera->camera_set_cover(1);
    enum CameraState state = CAMERA_STATE_NONE;

    state = camera->camera_get_state( CAMERA_ENCODE );
    qDebug()<< "CAMERA_ENCODE" << "=" << state;
    state = camera->camera_get_state( CAMERA_DECODE );
    qDebug()<< "CAMERA_DECODE" << "=" << state;
    state = camera->camera_get_state( CAMERA_PHOTO );
    qDebug()<< "CAMERA_PHOTO" << "=" << state;

    while( camera->camera_get_state(CAMERA_PHOTO) == CAMERA_PHOTO_BUZY);
    qDebug()<<"take photo free";

    state = camera->camera_get_state( CAMERA_ENCODE );
    qDebug()<< "CAMERA_ENCODE" << "=" << state;
    state = camera->camera_get_state( CAMERA_DECODE );
    qDebug()<< "CAMERA_DECODE" << "=" << state;
    state = camera->camera_get_state( CAMERA_PHOTO );
    qDebug()<< "CAMERA_PHOTO" << "=" << state;
}

void MainWindow::clickStartRecord()
{
    int ret = true;
    char name[30] = "kylin.mp4";
    enum CameraState state;

    char dev_name[8];
    if(Get_DevIndex(dev_name , sizeof(dev_name))!=0)
    {
        readoutHandle();
        return;
    }
    if(camera)
    {
        state = camera->camera_get_state(CAMERA_ENCODE);
        qDebug() << "camera state:" << state;
        if(state == CAMERA_ENCODE_STOP)
        {

            QAudioDeviceInfo deviceInfo = QAudioDeviceInfo::defaultInputDevice();
            qDebug()<<"audio device:"<<deviceInfo.deviceName();
            camera->camera_audio_init(deviceInfo);

            char photo_name[30] = "pre.jpg";
            camera->camera_take_photo(photo_name);
            enum CameraState state = CAMERA_STATE_NONE;
            while( camera->camera_get_state(CAMERA_PHOTO) == CAMERA_PHOTO_BUZY);

            ret = camera->camera_start_record(name, false);
            if(ret != true)
            {
                camera->camera_stop_record();
                return;
            }

            video_enable = 1;

            ui->label->setText("00:00:00");

            if(!pTimer)
            {
                pTimer = new QTimer;
                connect(pTimer,&QTimer::timeout,this,&MainWindow::updateRecordTime);
            }
            pTimer->setInterval(200);
            pTimer->start();

            ui->recordStartButton->hide();
            ui->recordStopButton->show();
        }
    }

}

void MainWindow::clickStopRecord()
{
    enum CameraState state;
    state = camera->camera_get_state(CAMERA_ENCODE);
    qDebug() << "camera state:" << state;
    if(state == CAMERA_ENCODE_START)
    {
        if(video_enable == 0)
            camera->camera_record_pause(false);

        camera->camera_stop_record();

        video_enable = 0;

        pTimer->stop();
        ui->label->setText("");

        ui->recordStartButton->show();
        ui->recordStopButton->hide();
    }
}

void MainWindow::clickCloseCamera()
{
    delete camera;
}

void MainWindow::clickStartCamera()
{
    //const char *in_devname = "/dev/video2";
    V4l2DeviceInfo device_info;

    camera = new KylinCamera(this);
    /*
    memcpy(device_info.dev_path, in_devname, strlen(in_devname)+1);
    KylinCamera::enum_device(&device_info);

    KylinCameraInfo camera_info;
    memcpy(camera_info.devname, in_devname, strlen(in_devname)+1);
    camera_info.format = V4L2_PIX_FMT_MJPEG;
    camera_info.width = 1920;
    camera_info.height = 1080;
    camera_info.fps = 30;
    */

    videoDisplay = camera->create(this, &camera_info);
    //videoDisplay->setWindowFlags(Qt::CustomizeWindowHint|Qt::FramelessWindowHint);
    //ui->verticalLayout->addWidget(videoDisplay);
    ui->horizontalLayout_3->addWidget(videoDisplay);
}


void MainWindow::clickAudioEnable()
{
    static char i = 0;
    if(i == 0) {
        camera->camera_audio_disable();
        i = 1;
    } else {
        for( QAudioDeviceInfo &deviceInfo: QAudioDeviceInfo::availableDevices(QAudio::AudioInput))
        {
            if(deviceInfo.deviceName().contains("Camera"))
            {
                qDebug()<<"audio device:"<<deviceInfo.deviceName();
                camera->camera_audio_init(deviceInfo);
                break;
            }
            else
            {
                 qDebug()<<deviceInfo.deviceName();
            }

        }
        i = 0;
    }
}

#if 1
void MainWindow::clickVideoEnable()
{
    enum CameraState state;
    state = camera->camera_get_state(CAMERA_ENCODE);
    qDebug() << "camera state:" << state;
    if(state == CAMERA_ENCODE_START)
    {
        if(video_enable == 1) {
            camera->camera_record_pause(true);
            pTimer->stop();
            video_enable = 0;
        } else {
            camera->camera_record_pause(false);
            pTimer->start();
            video_enable = 1;
        }
    }
}
#endif

void MainWindow::clickDisplayMirror()
{
    static int mirror = true;
    if(mirror == false){
        camera->camera_display_mirror(true);
         mirror = true;
    }
    else {
       camera->camera_display_mirror(false);
        mirror = false;
    }
}

void MainWindow::on_volumeSubButton_clicked()
{
#if 0
    qreal volume = camera->camera_audio_volume();
    qDebug()<<"volumeSubButton";
    qDebug()<<"old volume = "<<volume;
    volume-=0.1;
    qDebug()<<"volume = "<<volume;
    camera->camera_audio_volume_set(volume);
    volume = camera->camera_audio_volume();
    qDebug()<<"new volume = "<<volume;
#endif
}

void MainWindow::on_volumeAddButton_clicked()
{
#if 0
    qreal volume = camera->camera_audio_volume();
    qDebug()<<"volumeAddButton";
    qDebug()<<"old volume = "<<volume;
    volume+=0.1;
    qDebug()<<"volume = "<<volume;
    camera->camera_audio_volume_set(volume);
    volume = camera->camera_audio_volume();
    qDebug()<<"new volume = "<<volume;
#endif
}

void MainWindow::on_getStatusButton_clicked()
{
    enum CameraState state = CAMERA_STATE_NONE;
    for(int i = CAMERA_CAPTURE;i <= CAMERA_PHOTO;i++)
    {
        state = camera->camera_get_state( (enum CameraOptions)i );
        qDebug()<< i << "=" << state;
    }
}

void MainWindow::on_closeButton_clicked()
{

}

void MainWindow::Display_camera_info()
{
    KylinCameraInfo get_camera_info;
    camera->camera_get_param(&get_camera_info);
    char formatArray[] = { (char)(get_camera_info.format&0xff), (char)((get_camera_info.format>>8)&0xff),
                           (char)((get_camera_info.format>>16)&0xff), (char)((get_camera_info.format>>24)&0xff), 0 };
    QString string_info = formatArray +
            QString::number(get_camera_info.width) + "x" + QString::number(get_camera_info.height) + "," +
            QString::number(get_camera_info.fps);
    ui->lineEdit->setText(string_info);
}

void MainWindow::testOpenDev()
{

    //test by tangs;
    auto start = std::chrono::high_resolution_clock::now();
    if(camera)      //camera对象还没有delete掉
    {
        ui->horizontalLayout_3->removeWidget(videoDisplay);
        videoDisplay->setParent(nullptr);
        delete camera;
        camera = NULL;
    }

    camera = new KylinCamera(this);
    camera_info.fps=30;
    int iLen = strnlen(camera_info.devname , sizeof(camera_info.devname));
    if (iLen < sizeof(camera_info.devname)) iLen = iLen + 1;
    memcpy(camera_info.devname, camera_info.devname, iLen);          //要打开的摄像头名称
    videoDisplay = camera->create(this, &camera_info);
    ui->horizontalLayout_3->addWidget(videoDisplay);

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> elapsed  = end - start;
    LOG(CAMERA_LOG, NOTICE) <<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:MM:ss:zzz")<<" "<< __func__ <<": totalTimes="<< elapsed.count()/1000.0 <<" done";
}

void MainWindow::on_comboBox_activated(const QString &arg1)
{
    QString tmp_str = ui->comboBox->currentText();
    qDebug()<<tmp_str;

    TypePixFormats *pixfmt = &device_info.fmt_supported[itmp];
    int j,k;
    for(j = 0; j < 50; j++) {
        TypeFramesizes *fsize = &pixfmt->frm_sizes[j];
        if(fsize->frm_size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
            pixfmt->frm_sizes_len++;
            //qDebug() << "{ discrete: width = "<< fsize->frm_size.discrete.width
                          //<< ", height = " << fsize->frm_size.discrete.height << "}";
            QString string_num = QString::number(fsize->frm_size.discrete.width) + "x" + QString::number(fsize->frm_size.discrete.height);
            if( tmp_str == string_num ) {
                for(k = 0; k < 10; k++) {
                    struct v4l2_frmivalenum *fivals = &fsize->frm_ivals[k];
                    if (fivals->type == V4L2_FRMIVAL_TYPE_DISCRETE) {
                        //qDebug() << fivals->discrete.numerator << "/" << fivals->discrete.denominator;
                        camera_info.width = fsize->frm_size.discrete.width;
                        camera_info.height = fsize->frm_size.discrete.height;
                        camera_info.fps = fivals->discrete.denominator;
                        break;
                    }
                }
                break;
            }

        }
    }

    //重新打開，并设置参数
    //MainWindow::clickCloseCamera();
    //MainWindow::clickStartCamera();

    //设置参数

    {
      testOpenDev();
    }
    //camera->camera_set_param(&camera_info);
    //展示参数
    Current_Paramt();
}

int id_array[] = {
    WHITE_BALANCE,
    BRIGHTNESS,
    CONTRAST,
    SATURATION,
    HUE,
    SHARPNESS,
    BACKL_COMP,
    EXPOSURE_AUTO,
    EXPOSURE_ABSOLUTE
};
void MainWindow::on_comboBox_2_activated(const QString &arg1)
{
    QString tmp_str = ui->comboBox_2->currentText();
    int tmp_index = ui->comboBox_2->currentIndex();
    qDebug()<<tmp_str<<":"<<tmp_index;

    ctr_id = id_array[tmp_index];

    struct v4l2_queryctrl argp;
    camera->camera_query_contrl(ctr_id, &argp);
    //qDebug()<<"maximum:"<<argp.maximum<<",minimum:"<<argp.minimum;
    ui->horizontalSlider->setMaximum(argp.maximum);
    ui->horizontalSlider->setMinimum(argp.minimum);

    int cur_value;
    camera->camera_get_contrl(ctr_id, &cur_value);

    tmp_str = QString::number(cur_value);
    ui->lineEdit_2->setText(tmp_str);
}

void MainWindow::on_comboBox_2_activated(int index)
{

}

void MainWindow::on_horizontalSlider_valueChanged(int value)
{
    qDebug()<<value;
    QString str=QString::number(value,10);
    ui->lineEdit_2->setText(str);
    camera->camera_set_contrl(ctr_id, value);
}

void MainWindow::on_lineEdit_2_editingFinished()
{
    QString tmp_str = ui->lineEdit_2->text();
    qDebug()<<tmp_str;
    bool ok;
    int value = tmp_str.toInt(&ok,10);
    camera->camera_set_contrl(ctr_id, value);

    int cur_value;
    camera->camera_get_contrl(ctr_id, &cur_value);
    tmp_str = QString::number(cur_value);
    ui->lineEdit_2->setText(tmp_str);
}

//更新录像时间
void MainWindow::updateRecordTime()
{
    int hour = (camera->camera_get_record_time()/1000/60/60)%60;
    int min = (camera->camera_get_record_time()/1000/60)%60;
    int sec = (camera->camera_get_record_time()/1000)%60;

    QString str_hour = (hour >= 10) ? QString::number(hour) : "0" + QString::number(hour);
    QString str_min = (min >= 10) ? QString::number(min) : "0" + QString::number(min);
    QString str_sec = (sec >= 10) ? QString::number(sec) : "0" + QString::number(sec);
    QString str = str_hour + ":" + str_min + ":" + str_sec;
    ui->label->setText(str);
}

void MainWindow::readoutHandle()
{
    DIR *dir;
    struct dirent *dirp;
    int get_name,i,j,k;
    char tmp_dev[32];

    if(camera)
    {
        disconnect(videoDisplay,SIGNAL(readout()),this, SLOT(readoutHandle()));
        //connect(this,SIGNAL(readout()),this, SLOT(readoutHandle()));
    }

    qDebug()<<"readoutHandle()";

    //最小dev节点
    char dev_name[8];
    if(Get_DevIndex(dev_name,sizeof(dev_name))!=0) {     //没有找到设备节点
        qDebug()<<"not find camera device";

        if( ui->recordStartButton )
            ui->recordStartButton->hide();      //录像按键无效
        if( ui->recordStopButton )
            ui->recordStopButton->hide();       //停止录像按键无效

        if(camera)      //camera对象还没有delete掉
        {
            delete camera;
            camera = NULL;
        }

        //重新打开一个定时器，执行当前当前历程，反复寻找设备节点
        if(!cTimer)
        {
            cTimer = new QTimer;
            connect(cTimer,&QTimer::timeout,this,&MainWindow::readoutHandle);
            cTimer->start(1000);
        }

    }
    else {  //存在设备节点

        //如果之前打开了反复执行当前历程以选择设备节点的定时器，这里关闭它
        if(cTimer)
        {
            cTimer->stop();
            disconnect(cTimer,&QTimer::timeout,this,&MainWindow::readoutHandle);
            delete cTimer;
            cTimer = NULL;
        }

        //当前节点
        if( ui->comboBox_3 )
            ui->comboBox_3->setCurrentText(dev_name);

        int devLen = strnlen(tmp_dev,sizeof(tmp_dev));
        if (devLen <sizeof(tmp_dev)) devLen = devLen +1;
        memcpy(camera_info.devname, tmp_dev, devLen);


        //重新打开摄像头并设置参数
        on_comboBox_3_activated(dev_name);

        if( ui->recordStartButton )
            ui->recordStartButton->show();      //恢复录像按键

        connect(videoDisplay,SIGNAL(readout()),this, SLOT(readoutHandle()));
    }


}

void MainWindow::lockingHandle(bool lock)
{
    char tmp_dev[32];
    char dev_name[8];

    qDebug()<<"lockingHandle()";
    if(lock) {
        if(camera)
        {
            qDebug() << "0 " << QDateTime::currentDateTime().toString("hh:MM:ss:zzz");
            clickStopRecord();
            disconnect(videoDisplay,SIGNAL(readout()),this, SLOT(readoutHandle()));
            //connect(this,SIGNAL(readout()),this, SLOT(readoutHandle()));
            qDebug() << "1 " << QDateTime::currentDateTime().toString("hh:MM:ss:zzz");
            delete camera;
            qDebug() << "2 " << QDateTime::currentDateTime().toString("hh:MM:ss:zzz");
            camera = NULL;
        }
    }
    else {
        //if(!camera)
            readoutHandle();
    }

}

void MainWindow::on_FlashButton_clicked()
{
    //默认节点
    char dev_name[8];
    Get_DevIndex(dev_name,sizeof(dev_name));
    //ui->comboBox_3->setCurrentText(dev_name);
}

void MainWindow::on_comboBox_3_activated(const QString &arg1)
{
    //close the old device
    if(camera)
    {
        delete camera;
        camera = NULL;
    }

    camera = new KylinCamera(this);

    //device name
    char in_devname[16] = "/dev/";
    //strcat(in_devname,arg1.toLatin1().data());
    strncat(in_devname ,arg1.toLatin1().data() ,  sizeof(in_devname) - strnlen(in_devname,sizeof(in_devname)) -1);
    qDebug()<<"use camera device "<<in_devname;

    Enum_Device(in_devname , strnlen(in_devname , sizeof(in_devname)));    //重新枚举摄像头信息

    //重新打开摄像头并设置默认参数
    int iLen=strnlen(in_devname,sizeof(in_devname));
    if(iLen<sizeof(in_devname)) iLen = iLen+1;;
    memcpy(camera_info.devname, in_devname, iLen);

    videoDisplay = camera->create(this, &camera_info);
    qDebug()<<"camera->create";
    if(videoDisplay==NULL)
    {
        delete camera;
        camera = NULL;
        qDebug()<<"delete camera";
        readoutHandle();
    }
    else {
        //videoDisplay->setWindowFlags(Qt::CustomizeWindowHint|Qt::FramelessWindowHint);
        //ui->verticalLayout->addWidget(videoDisplay);
        ui->horizontalLayout_3->addWidget(videoDisplay);

        //获取并设置默认参数
        Current_Paramt();
    }

}


void MainWindow::on_checkBox_clicked()
{
    if(ui->checkBox->isChecked())
    {
        camera->camera_set_contrl(V4L2_CID_AUTO_WHITE_BALANCE, V4L2_WHITE_BALANCE_AUTO);
    }
    else {
        camera->camera_set_contrl(V4L2_CID_AUTO_WHITE_BALANCE, V4L2_WHITE_BALANCE_MANUAL);
    }

}
