/*
    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 <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>

#include "term_pv.h"

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

      res = fwrite(data, 1, size, tm->io_file.stream);

      if (ferror(tm->io_file.stream) || res < 0)
	{
	  tm->ioerr = errno;
	  break;
	}

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

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

  while (res <= 0)
    {
      res = fread(&c, 1, 1, tm->io_file.stream);

      if (ferror(tm->io_file.stream) || res < 0)
	{
	  tm->ioerr = errno;
	  return -1;
	}
    }

  return c;
}

static TERMUI_TERMIO_FCN_POLLFD(termui_file_pollfd)
{
  return fileno(tm->io_file.stream);
}

static TERMUI_TERMIO_FCN_CLEANUP(termui_file_cleanup)
{
}

termui_err_t
termui_file_io_init(struct termui_term_s *tm, FILE *file,
		    const char *type)
{
  memset(tm->type, 0, TERMUI_TYPESTR_MAXLEN);
  tm->ioerr = 0;
  tm->io_file.stream = file;

  /* register tty operations in term object */
  tm->s_write = termui_file_write;
  tm->s_read = termui_file_read;
  tm->s_pollfd = termui_file_pollfd;
  tm->s_cleanup = termui_file_cleanup;

  tm->s_getsize = (termui_termio_getsize_t*)term_err;

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

  return 0;
}

