/*
 * qio_devices.hpp
 *
 *  Created on: 13 янв. 2020 г.
 *      Author: alexrayne <alexraynepe196@gmail.com>
  ------------------------------------------------------------------------
    Copyright (c) alexrayne

   All rights reserved.
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
   - Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   - Neither the name of ARM nor the names of its contributors may be used
     to endorse or promote products derived from this software without
     specific prior written permission.
   *
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE. *
  ------------------------------------------------------------------------
 * this is a Qt StdIO devices
 */

#include <cassert>
#include "qio_devices.hpp"



//***************************************************************************
//                      StdIO_Device
QConsoleIODeviceBase::QConsoleIODeviceBase(void* buf, unsigned bufsize, QObject *parent)
: QObject(parent)
, inherited_io()
, avail()
, cin(buf, bufsize, 0)
{
}

void QConsoleIODeviceBase::on_input(const QByteArray &data) {
    if (data.size() <= 0)
        return;
    cin.WriteData( data.constData(), data.size() );
    avail.release();
}

int QConsoleIODeviceBase::get_char(){
    if ( !cin.isEmpty() )
        return cin.pop_char();

    if ( get_wait(toInfinite) > 0 )
    if ( !cin.isEmpty() )
        return cin.pop_char();

    return -1;
}

int QConsoleIODeviceBase::get_wait(unsigned to_ms) {
    if (to_ms == 0)
        return cin.DataSize();

    if (avail.tryAcquire(1, to_ms))
    //if ( cin.waitForReadyRead( to_ms ))
    {
        return cin.DataSize();
    }
    else
        return 0;
}

//StdOUT_Device
//* блокирующая печать
int QConsoleIODeviceBase::putChar(int ch) {
    emit signal_output( QByteArray( 1, (char)ch ) );
    return 1;
}

//*  неблокирующая печать
int QConsoleIODeviceBase::postData ( const void* str, unsigned len){
    return putData(str, len);
}

//HAL_OUTBlock_Device
int QConsoleIODeviceBase::puts( const char* str) {
    auto len = strlen(str);
    emit signal_output( QByteArray( str, len ) );
    return len;
}

//*  \return - длинна отправленного участка
int QConsoleIODeviceBase::putData ( const void* str, unsigned len) {
    emit signal_output( QByteArray( (const char*)str, len ) );
    return len;
}



//***************************************************************************
//                      QSockIODevice

#include <sys/types.h>
#include <sys/socket.h>
// provide : S_IFSOCK
#include <sys/stat.h>
#include <netinet/in.h>
#include <sys/ioctl.h>

#include <fcntl.h>
#include <unistd.h>
#include <sys/select.h>


//-----------------------------------------------------------------------------
QSockIODevice::QSockIODevice( QObject *parent )
:inherited(parent)
{
}

QSockIODevice::QSockIODevice(sockid_t id, QObject *parent)
:inherited(parent)
{
    init(id);
}

//virtual 
QSockIODevice::~QSockIODevice(){
    close();
}


bool QSockIODevice::init(sockid_t x){
    return setSocketDescriptor(x);
}


int QSockIODevice::get_char(){
    char c;
    if ( getChar(&c) )
            return c;
    return -1;
}

int QSockIODevice::get_wait(unsigned to_ms){
    if (to_ms == 0)
        return bytesAvailable();
    if (!isValid())
        return -1;
    if (waitForReadyRead(to_ms))
        return bytesAvailable();
    else
        return 0;
}

// блокирующий прием
//*  \return - длинна полученного участка
int QSockIODevice::getData ( void* dst, unsigned len){
    auto res = read((char*)dst, len);
    return res;
}
//*  ожидание amount доступных символов
int QSockIODevice::get_waitfor(unsigned amount, unsigned to_ms){
    int count = bytesAvailable();
    if (to_ms == 0){
        return count;
    }

    if (!isValid())
        return -1;

    while (count < amount) {
        if (waitForReadyRead(to_ms)){
            count = bytesAvailable();
        }
        else
            break;
    }
    return count;
}

//* блокирующая печать
int QSockIODevice::putChar(int ch){
    if (inherited::putChar(ch))
        return 1;
    return 0;
}

//*  неблокирующая печать
int QSockIODevice::postData ( const void* str, unsigned len){
    return write((const char*) str, len);
}

//* блокирующая печать
int QSockIODevice::puts( const char* str){
    return putData(str, strlen(str) );
}

//*  \return - длинна отправленного участка
int QSockIODevice::putData ( const void* str, unsigned len){
    return write((const char*) str, len);
}

//*  ожидание доступности печати
//*  \return - количество байт возможных для неблокирующей печати
int QSockIODevice::put_wait(unsigned to){
    // TODO hardcoded 1k space availed. maybe better provide net MTU size.
    return 1<<10;
}

//*  почти тоже put_wait, ждет полного опустошения
int QSockIODevice::put_flush(unsigned to){
    while (bytesToWrite() > 0){
        if (!isValid())
            return -1;
        if ( !waitForBytesWritten(to) )
            break;
    }
    return bytesToWrite();
}

//*  очищает буфер, прерывая текущую отправку
int QSockIODevice::put_drop(){
    // TODO QSocket can`t do it
    return 0;
}



