#include "ft232_reign.h"
#include "ui_ft232_reign.h"

#include <i2c.h>

#include <qdatetime.h>
#include <qthread.h>

#define FTDI_ERROR(info)  {   toLog(info);  return; }

QString last_write_data = "00";

QString hex_values[16] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };

bool tmr_on = false;
bool out = false;

ft232_reign::ft232_reign(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ft232_reign)
{
    ui->setupUi(this);    
    log = "";
    tmr = new QTimer();
    tmr->setInterval(500);
    tmr->setSingleShot(false);
    tmr->start();
    QObject::connect(tmr, SIGNAL(timeout ()), this, SLOT(tmr_fxn()));
    on_reflesh_com_clicked();
    on_com_int_line_currentIndexChanged(ui->com_int_line->currentIndex());
    i2c_hid_descr[10] = 2;
    i2c_hid_descr[11] = 0;
}

ft232_reign::~ft232_reign()
{
    i2c_close();
    delete ui;    
}

void ft232_reign::on_pushButton_clicked()
{
    //i2c_example();
    //char desc[1024], serial[1024];
    //i2c_open_index_port (0, desc, serial);

    if (bitbang_open (0, 1, 255) == 0)
        tmr_on = 1;
}

void ft232_reign::on_pushButton_2_clicked()
{
    //i2c_example();
    //bitbang_close();
    //tmr_on = 0;
}

void ft232_reign::toLog(QString info)
{
    log = QTime::currentTime().toString("HH:mm:ss") + "\t" + info + "\n" + log;
    ui->log->setText("LOG\n\n" + log);
}

QString ft232_reign::char_to_str(char *data, int len)
{
    QString str = "";
    for (int i = 0; i < len; i++)   {
        if (data[i] == 0x00)
            break;
        str = str + data[i];
    }
    return str;
}

void ft232_reign::on_clr_log_clicked()
{
    log = "";
    ui->log->setText("LOG\n\n");
}

void ft232_reign::on_connect_clicked()
{
    int result = 0;
    if (ui->connect->text() == "Connect")   {
        res = i2c_open(ui->i2c_clk->value(), ui->i2c_index->value(), (ui->i2c_port->currentIndex() + 1));
        qDebug ("Connecting to FTDI device, clk %d, index %d, port %d. RETURN %d", ui->i2c_clk->value(), ui->i2c_index->value(), (ui->i2c_port->currentIndex() + 1), res);
        if (res == 0)    {
            ui->connect->setText("Disconnect");
            toLog ("CONNECTING TO DEVICE OK, " + ui->i2c_port->currentText() + ", CLK " + QString::number(ui->i2c_clk->value()) + ", INDEX " + QString::number(ui->i2c_index->value()));
        }
        else    {
            FTDI_ERROR("ABORT_OPEN_CHANNEL, ERROR " + QString::number(res));
        }
    }
    else    {
        i2c_close();
        ui->connect->setText("Connect");
        toLog ("DEVICE DISCONNECTED");
    }
}

void ft232_reign::on_i2c_length_valueChanged(int arg1)
{
    QString mask = "HH";    int last_mask_len;  QString last_data;
    for (int i = 1; i < arg1; i++)
        mask = mask + " HH";
    last_mask_len = ui->i2c_write_data->inputMask().length();
    last_data = ui->i2c_write_data->text();
    ui->i2c_write_data->setInputMask(mask);
    if (last_mask_len < mask.length())  {
        for (int i = 0; i < ((mask.length() - last_mask_len) / 3); i++)
            last_data = last_data + " 00";
        ui->i2c_write_data->setText(last_data);
    }
}

void ft232_reign::on_i2c_write_data_textChanged(const QString &arg1)
{
    if (arg1.length() != (3 * ui->i2c_length->value() - 1))
        ui->i2c_write_data->setText(last_write_data);
    else
        last_write_data = ui->i2c_write_data->text();
}

void ft232_reign::on_i2c_write_clicked()
{
    QString str = ui->i2c_write_data->text();
    for (int i = 0; i < ui->i2c_length->value(); i++)
        data[i] = str.mid(i*3, 2).toInt(NULL, 16);
    res = i2c_tx (ui->i2c_adress->value(), (char*)data, ui->i2c_length->value(), 1, 1);    //res = I2C_DeviceWrite(reign, ui->i2c_adress->value(), ui->i2c_length->value(), data, &transfer_len, 0x07);
    if (res == 10/*FT_DEVICE_NOT_FOUND*/) {
        toLog ("I2C DEVICE WITH ADRESS 0x" + QString::number(ui->i2c_adress->value(), 16) + " NOT ASK (TX)");
        return;
    }
    if (res != 0/*FT_OK*/)
        FTDI_ERROR("ABORT_TRANSMIT, ERROR " + QString::number(res));
    str = "I2C TRANSMIT TO 0x" + QString::number(ui->i2c_adress->value(), 16) + " " + QString::number(ui->i2c_length->value()) + " BYTES:\t";
    for (int i = 0; i < ui->i2c_length->value(); i++)
        str = str + " " + QString::number(data[i], 16);
    toLog(str);
}

void ft232_reign::on_i2c_read_clicked()
{
    QString str;
    res = i2c_rx (ui->i2c_adress->value(), (char*)data, ui->i2c_length->value(), 1, 1);    //res = I2C_DeviceRead(reign, ui->i2c_adress->value(), ui->i2c_length->value(), data, &transfer_len, 0x0B);
    if (res == 10/*FT_DEVICE_NOT_FOUND*/) {
        toLog ("I2C DEVICE WITH ADRESS 0x" + QString::number(ui->i2c_adress->value(), 16) + " NOT ASK (RX)");
        return;
    }
    if (res != 0/*FT_OK*/)
        FTDI_ERROR("ABORT_RECEIVE, ERROR " + QString::number(res));
    str = "I2C RECEIVE FROM 0x" + QString::number(ui->i2c_adress->value(), 16) + " " + QString::number(ui->i2c_length->value()) + " BYTES:\t";
    for (int i = 0; i < ui->i2c_length->value(); i++)
        str = str + " " + QString::number(data[i], 16);
    toLog(str);
}

void ft232_reign::on_read_i2c_hid_desc_clicked()
{
    toLog ("READING I2C HID DESCRIPTOR");
    ui->i2c_length->setValue(2);
    ui->i2c_write_data->setText("01 00");
    on_i2c_write_clicked();
    QThread::msleep(100);
    ui->i2c_length->setValue(30);
    on_i2c_read_clicked();
    for (int i = 0; i < 30; i++)    {
        i2c_hid_descr[i] = data[i];
    }
    toLog ("------------------------------------------");
}

void ft232_reign::on_read_hid_report_desc_clicked()
{
    toLog ("READING HID REPORT DESCRIPTOR");
    ui->i2c_length->setValue(2);
    QString reg = hex_values[(i2c_hid_descr[6]>>4) & 0xF] + hex_values[(i2c_hid_descr[6]>>0) & 0xF] + " " + \
                  hex_values[(i2c_hid_descr[7]>>4) & 0xF] + hex_values[(i2c_hid_descr[7]>>0) & 0xF];
    ui->i2c_write_data->setText(reg);
    on_i2c_write_clicked();
    QThread::msleep(100);
    ui->i2c_length->setValue((i2c_hid_descr[4] & 0xFF) + (i2c_hid_descr[5] & 0xFF) * 256);
    on_i2c_read_clicked();
    toLog ("------------------------------------------");
}

void ft232_reign::on_read_input_report_int_clicked()
{
    toLog ("READING INPUT REPORT (INTERRUPT MODE)");
    ui->i2c_length->setValue((i2c_hid_descr[10] & 0xFF) + (i2c_hid_descr[11] & 0xFF) * 256);
    on_i2c_read_clicked();
    toLog ("------------------------------------------");
}

void ft232_reign::on_read_input_report_cmd_clicked()
{
    toLog ("READING INPUT REPORT (COMMAND MODE)");
    ui->i2c_length->setValue(6);
    QString reg = hex_values[(i2c_hid_descr[16]>>4) & 0xF] + hex_values[(i2c_hid_descr[16]>>0) & 0xF] + " " + \
                  hex_values[(i2c_hid_descr[17]>>4) & 0xF] + hex_values[(i2c_hid_descr[17]>>0) & 0xF];
    reg = reg + " 10 02 ";  //  COMMAND OPCODE - 2 (INPUT REPORT REQUEST), TYPE 01 - INPUT
    reg = reg + hex_values[(i2c_hid_descr[18]>>4) & 0xF] + hex_values[(i2c_hid_descr[18]>>0) & 0xF] + " " + \
                hex_values[(i2c_hid_descr[19]>>4) & 0xF] + hex_values[(i2c_hid_descr[19]>>0) & 0xF];
    ui->i2c_write_data->setText(reg);
    on_i2c_write_clicked();
    QThread::msleep(100);
    ui->i2c_length->setValue((i2c_hid_descr[10] & 0xFF) + (i2c_hid_descr[11] & 0xFF) * 256);
    on_i2c_read_clicked();
    toLog ("------------------------------------------");
}


void ft232_reign::on_reflesh_com_clicked()
{
    com_list = QSerialPortInfo::availablePorts();
    //QObject::disconnect(ui->com_list, SIGNAL(currentIndexChanged(int)), this, SLOT(on_com_list_currentIndexChanged(int)));
    for (int i = ui->com_list->count(); i >=0; i--)
        ui->com_list->removeItem(i);
    for (int i = 0; i < com_list.length(); i++)
        ui->com_list->addItem(com_list.at(i).portName());
    //if (com_list.length() > 0)  {
        //QObject::connect(ui->com_list, SIGNAL(currentIndexChanged(int)), this, SLOT(on_com_list_currentIndexChanged(int)));
    if (ui->com_list->currentIndex() >= 0)
        ui->com_list->setToolTip(com_list.at(ui->com_list->currentIndex()).description());
    //}
}

void ft232_reign::on_com_list_currentIndexChanged(int index)
{
    if (index >= 0)
        ui->com_list->setToolTip(com_list.at(index).description());
}

void ft232_reign::on_com_connect_clicked()
{
    QWidget* widgets_locked[] = { ui->com_list, ui->reflesh_com };
    QWidget* widgets_unlocked[] = { ui->com_int_line, ui->en_int_evt, ui->label_int };
    if (ui->com_connect->text() == "Connect")   {
        com.setPortName(com_list.at(ui->com_list->currentIndex()).portName());
        if (com.open(QSerialPort::ReadWrite))   {
            com.setParity(QSerialPort::NoParity);
            com.setDataBits(QSerialPort::Data8);
            com.setStopBits(QSerialPort::OneStop);
            com.setFlowControl(QSerialPort::NoFlowControl);
            com.setBaudRate(921600);
            ui->com_connect->setText("Disconnect");
            toLog ("COM " + com.portName() + " OPENED OK");
            tmr_on = true;
        }
        else
            toLog ("COM " + com.portName() + " OPEN ERROR");
    }
    else    {
        com.close();
        toLog ("COM " + com.portName() + " CLOSED");
        ui->com_connect->setText("Connect");
        tmr_on = false;
    }
    for (int i = 0; i < sizeof(widgets_locked)/sizeof(QWidget*); i++)
        widgets_locked[i]->setEnabled(!com.isOpen());
    for (int i = 0; i < sizeof(widgets_unlocked)/sizeof(QWidget*); i++)
        widgets_unlocked[i]->setEnabled(com.isOpen());
}

void ft232_reign::on_com_int_line_currentIndexChanged(int index)
{
    switch (index)  {
        case 0: int_mask = QSerialPort::DataSetReadySignal;         break;
        case 1: int_mask = QSerialPort::DataCarrierDetectSignal;    break;
        case 2: int_mask = QSerialPort::ClearToSendSignal;          break;  }
    qDebug ("COM INT MASK %u", int_mask);
}

void ft232_reign::tmr_fxn()
{
    if (tmr_on == false)
        return;
    int inputs = com.pinoutSignals();
    if (((inputs & int_mask) != 0) && (out == false))    {
        out = true;
        ui->label_int->setText("INT ON (GND)");

    }
    else if (((inputs & int_mask) == 0) && (out == true))   {
        out = false;        
        ui->label_int->setText("INT OFF (+3.3)");
    }
    if (out == true)   {
        if (ui->en_int_evt->isChecked())            {
            on_read_input_report_int_clicked();
            if ((data[0] == 0) && (data[1] == 0))   {
                on_read_i2c_hid_desc_clicked();
                on_read_hid_report_desc_clicked();
                on_write_output_report_reg_clicked();
            }
        }
    }
    /*if (out != ui->int_line->isChecked())   {
        if (out)
        //ui->int_line->setCheckable(true);
        //ui->int_line->setChecked(out);
        //ui->int_line->setCheckable(false);
    }*/
    //qDebug ("COM LINES STATE: %u", inputs);
    /*if (tmr_on == 0)
        return;
    char rd[10];
    bitbang_read(rd);
    qDebug ("Reading from FTDI bitbang: %x, %x, %x, %x", rd[0], rd[1], rd[2], rd[3]);*/
}

void ft232_reign::on_write_output_report_reg_clicked()
{
    //if ((I2C_INPUT_DATA[0] == 5) && (I2C_INPUT_DATA[1] == 0)
    //        && (I2C_INPUT_DATA[2] == 32) && (I2C_INPUT_DATA[3] == 3)
    //        && (I2C_INPUT_DATA[4] == 6) && (I2C_INPUT_DATA[5] == 0)
    //        && (I2C_INPUT_DATA[6] == 1) && (I2C_INPUT_DATA[7] == 0))  begin
    char data_led = 0;
    if (ui->NUM->isChecked())       data_led = data_led | 1;
    if (ui->CAPS->isChecked())      data_led = data_led | 2;
    if (ui->SCROOL->isChecked())    data_led = data_led | 4;
    toLog ("WRITING OUTPUT REPORT (TO OUTPUT ADRESS)");
    ui->i2c_length->setValue(5);
    QString reg = hex_values[(i2c_hid_descr[12]>>4) & 0xF] + hex_values[(i2c_hid_descr[12]>>0) & 0xF] + " " + \
                  hex_values[(i2c_hid_descr[13]>>4) & 0xF] + hex_values[(i2c_hid_descr[13]>>0) & 0xF];
    reg = reg + " 01 00 ";  //  DATA LEN - 1
    reg = reg + hex_values[(data_led>>4) & 0xF] + hex_values[(data_led>>0) & 0xF];
    ui->i2c_write_data->setText(reg);
    on_i2c_write_clicked();
    toLog ("------------------------------------------");
}

void ft232_reign::on_NUM_toggled(bool checked)
{
    on_write_output_report_reg_clicked();
}

void ft232_reign::on_CAPS_clicked()
{
    on_write_output_report_reg_clicked();
}

void ft232_reign::on_SCROOL_clicked()
{
    on_write_output_report_reg_clicked();
}

void ft232_reign::on_cmd_reset_clicked()
{
    //if ((I2C_INPUT_DATA[0] == 5) && (I2C_INPUT_DATA[1] == 0) && (I2C_INPUT_DATA[2] == 0) && (I2C_INPUT_DATA[3] == 1))
    toLog ("WRITING RESET COMMAND");
    ui->i2c_length->setValue(4);
    QString reg = hex_values[(i2c_hid_descr[16]>>4) & 0xF] + hex_values[(i2c_hid_descr[16]>>0) & 0xF] + " " + \
                  hex_values[(i2c_hid_descr[17]>>4) & 0xF] + hex_values[(i2c_hid_descr[17]>>0) & 0xF];
    reg = reg + " 00 01";  //  COMMAND OPCODE - 1 (RESET), OTHER FIELDS - ZERO
    ui->i2c_write_data->setText(reg);
    on_i2c_write_clicked();
    toLog ("------------------------------------------");
}

void ft232_reign::on_write_output_report_cmd_clicked()
{
    char data_led = 0;
    if (ui->NUM->isChecked())       data_led = data_led | 1;
    if (ui->CAPS->isChecked())      data_led = data_led | 2;
    if (ui->SCROOL->isChecked())    data_led = data_led | 4;
    toLog ("WRITING OUTPUT REPORT (COMMAND)");
    ui->i2c_length->setValue(9);
    QString reg = hex_values[(i2c_hid_descr[16]>>4) & 0xF] + hex_values[(i2c_hid_descr[16]>>0) & 0xF] + " " + \
                  hex_values[(i2c_hid_descr[17]>>4) & 0xF] + hex_values[(i2c_hid_descr[17]>>0) & 0xF];
    reg = reg + " 20 03 ";  //  DATA LEN - 1
    reg = reg + hex_values[(i2c_hid_descr[18]>>4) & 0xF] + hex_values[(i2c_hid_descr[18]>>0) & 0xF] + " " + \
                hex_values[(i2c_hid_descr[19]>>4) & 0xF] + hex_values[(i2c_hid_descr[19]>>0) & 0xF];
    reg = reg + " 01 00 ";
    reg = reg + hex_values[(data_led>>4) & 0xF] + hex_values[(data_led>>0) & 0xF];
    ui->i2c_write_data->setText(reg);
    on_i2c_write_clicked();
    toLog ("------------------------------------------");
}

void ft232_reign::on_read_input_report_reg_clicked()
{
    toLog ("READING INPUT REPORT (ADRESS)");
    ui->i2c_length->setValue(2);
    QString reg = hex_values[(i2c_hid_descr[8]>>4) & 0xF] + hex_values[(i2c_hid_descr[8]>>0) & 0xF] + " " + \
                  hex_values[(i2c_hid_descr[9]>>4) & 0xF] + hex_values[(i2c_hid_descr[9]>>0) & 0xF];
    ui->i2c_write_data->setText(reg);
    on_i2c_write_clicked();
    QThread::msleep(100);
    ui->i2c_length->setValue((i2c_hid_descr[10] & 0xFF) + (i2c_hid_descr[11] & 0xFF) * 256);
    on_i2c_read_clicked();
    toLog ("------------------------------------------");
}
