/*
    This file is part of libtermui.

    libtermui is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    libtermui is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with libtermui.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2006, Alexandre Becoulet <alexandre.becoulet@free.fr>

*/

#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>

#include "term_pv.h"
#include <termui/term_keys.h>

static TERMUI_TERMIO_FCN_WRITE(termui_rawfd_write)
{
  while (size)
    {
      termui_ssize_t res;

      res = write(tm->io_rawfd.fd_out, data, size);

      if (res < 0)
	{
	  tm->ioerr = errno;
	  break;
	}

      assert(res <= size);
      size -= res;
    }
}

static TERMUI_TERMIO_FCN_READ(termui_rawfd_read)
{
  termui_ssize_t res = 0;
  uint8_t c;

  while (res <= 0)
    {
      res = read(tm->io_rawfd.fd_in, &c, 1);

      if (res < 0)
	{
	  if (errno == EINTR)
	    continue;
	  tm->ioerr = errno;
	  return -1;
	}
    }

  return c;
}

static TERMUI_TERMIO_FCN_POLLFD(termui_rawfd_pollfd)
{
  return tm->io_rawfd.fd_in;
}

static TERMUI_TERMIO_FCN_CLEANUP(termui_rawfd_cleanup)
{
}

termui_err_t
termui_rawfd_io_init(struct termui_term_s *tm, int32_t fd_in,
		     int32_t fd_out, const char *type)
{
  memset(tm->type, 0, TERMUI_TYPESTR_MAXLEN);
  tm->ioerr = 0;
  tm->io_rawfd.fd_in = fd_in;
  tm->io_rawfd.fd_out = fd_out;

  /* register tty operations in term object */
  tm->s_write = termui_rawfd_write;
  tm->s_read = termui_rawfd_read;
  tm->s_pollfd = termui_rawfd_pollfd;
  tm->s_cleanup = termui_rawfd_cleanup;

  tm->s_getsize = (termui_termio_getsize_t*)term_err;

  strncpy(tm->type, type, TERMUI_TYPESTR_MAXLEN);
  termui_term_set(tm);

  return 0;
}

