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

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

termui_err_t term_err(void)
{
  return -EINVAL;
}

termui_err_t termui_term_set(struct termui_term_s *tm)
{
  const char *type = tm->type;
  termui_err_t err = 0;

  termui_term_set_none(tm);

  if (type)
    {
      if (!strcasecmp(type, "dumb"))
	;

      else if (!strcasecmp(type, "xterm") ||
	       !strcasecmp(type, "rxvt") ||
	       !strcasecmp(type, "linux") ||
	       !strcasecmp(type, "screen"))
	err = termui_term_set_xterm(tm);

      else if (!strcasecmp(type, "vt100"))
	err = termui_term_set_vt100(tm);

      else if (!strcasecmp(type, "vt102"))
	err = termui_term_set_vt102(tm);
      else
	err = -EINVAL;
    }

  return err;
}

TERMUI_TERM_FCN_GETSIZE(termui_term_getsize)
{
  termui_err_t res = -ENOSYS;

  /* try to get size from io */
  if (tm->s_getsize && !(res = tm->s_getsize(tm, x, y)))
    return res;

  /* try to get size from terminal driver */
  if (tm->t_getsize)
    res = tm->t_getsize(tm, x, y);

  return res;
}

/* behavior process */

termui_err_t
termui_term_process(struct termui_term_behavior_s *bhv)
{
  struct termui_term_s *tm = bhv->tm;
  termui_key_t k = termui_term_readkey(tm);

  if (k >= 0)
    {
      termui_term_keyevent_t *ev = bhv->keyevent[k];

      if (ev)
	{
	  termui_err_t res = ev(k, bhv);

	  if (res >= 0)
	    bhv->lastkey = k;

	  return res;
	}
      
      return -ENOTSUP;
    }

  return k;
}

