/*
    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 2010, Alexandre Becoulet <alexandre.becoulet@free.fr>

*/

#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <assert.h>
#include <libssh/libssh.h>

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

static TERMUI_TERMIO_FCN_GETSIZE(termui_ssh_getsize)
{
  // FIXME
  return -EIO;
}

static TERMUI_TERMIO_FCN_WRITE(termui_ssh_write)
{
  termui_ssize_t res = channel_write(tm->io_ssh.channel, data, size);

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

static TERMUI_TERMIO_FCN_READ(termui_ssh_read)
{
  uint8_t c;
  termui_ssize_t res = channel_read(tm->io_ssh.channel, &c, 1, 0);

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

  return c;
}

static TERMUI_TERMIO_FCN_POLLFD(termui_ssh_pollfd)
{
  return ssh_get_fd(tm->io_ssh.session);
}

static TERMUI_TERMIO_FCN_CLEANUP(termui_ssh_cleanup)
{
}

termui_err_t
termui_libssh_io_init(struct termui_term_s *tm,
		      ssh_session s, ssh_channel c)
{
  memset(tm, 0, sizeof(*tm));
  tm->io_ssh.session = s;
  tm->io_ssh.channel = c;

  /* register ssh operations in term object */
  tm->s_write = termui_ssh_write;
  tm->s_read = termui_ssh_read;
  tm->s_pollfd = termui_ssh_pollfd;
  tm->s_cleanup = termui_ssh_cleanup;
  tm->s_getsize = termui_ssh_getsize;

  /* set terminal type and associated terminal operations */

  // FIXME
  strncpy(tm->type, "xterm", TERMUI_TYPESTR_MAXLEN);

  termui_term_set(tm);

  return 0;
}

