/* Troll OS -- The Troll Operating System
*  Copyright (C) 2012  Matthew Caswell
*
*  This program 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.
*
*  This program 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 this program.  If not, see <http://www.gnu.org/licenses/>. */

#include <kbdus.h>
#include <monitor.h>
#include <kb.h>
#include <kernel_state.h>

int int01_flag=0;
int get_kb_ok=1;
int is_shift=0;
KB_t kbuf;

char getch_keys_gets()
{
  int i = strlen(kbuf.read);
  int n = strlen(kbuf.write);
  char c = ' ';

  if(i!=0 && n!=0){
    c = kbuf.read[i];
  }else{
    return -'1';
  }
  return c;
}
char getch_keys()
{
  int i = strlen(kbuf.read);
  int n = strlen(kbuf.write);
  char c = ' ';

  if(i!=0 && n!=0){
    c = kbuf.read[i];
  }else{
    return -'1';
  }
  return c;
}
char *gets(char *buf)
{
  while((!get_kb_ok)){
    hlt();
  }
  get_kb_ok=0;
  int i;
  int c;
  buf[0] = '\0';
  i = 0;
  // DEBUG
  kbuf.read = '\0';
  kbuf.write = '\0';
  while (1) {
    c = getch_keys_gets();
    if (c == -'1')
      hlt();
    if (c == '\r' || c == '\n') {
      break;
    }
    if (c == '\b' || c == 0x7f) {
      if (i > 0) {
        i--;
        buf[i] = '\0';
      }
      continue;
    }
    buf[i++] = c;
  }
  buf[i] = '\0';
  get_kb_ok=1;
  return buf;
}

static void write_kbd(unsigned adr, unsigned data)
{
	unsigned long timeout;
	unsigned stat;

	/* Linux code didn't have a timeout here... */
	for(timeout = 500000L; timeout != 0; timeout--)
	{
		stat = inb(0x64);
		/* loop until 8042 input buffer empty */
		if((stat & 0x02) == 0)
			break;
	}
	if(timeout != 0)
		outb(adr, data);
}

unsigned convert(unsigned key)
{

	static unsigned short kbd_status, saw_break_code;

	unsigned char temp;

	/* check for break key (i.e. a key is released) */
	if(key >= 0x80)
	{
		saw_break_code = 1;
		key &= 0x7F;
	}
	/* the only break codes we're interested in are Shift, Ctrl, Alt */
	if(saw_break_code)
	{
		if(key == RAW1_LEFT_ALT || key == RAW1_RIGHT_ALT)
			kbd_status &= ~KBD_META_ALT;
		else if(key == RAW1_LEFT_CTRL || key == RAW1_RIGHT_CTRL)
			kbd_status &= ~KBD_META_CTRL;
		else if(key == RAW1_LEFT_SHIFT || key == RAW1_RIGHT_SHIFT)
			kbd_status &= ~KBD_META_SHIFT;
		saw_break_code = 0;
		return 0;
	}
	/* it's a make key: check the "meta" keys, as above */
	if(key == RAW1_LEFT_ALT || key == RAW1_RIGHT_ALT)
	{
		kbd_status |= KBD_META_ALT;
		return 0;
	}
	if(key == RAW1_LEFT_CTRL || key == RAW1_RIGHT_CTRL)
	{
		kbd_status |= KBD_META_CTRL;
		return 0;
	}
	if(key == RAW1_LEFT_SHIFT || key == RAW1_RIGHT_SHIFT)
	{
		kbd_status |= KBD_META_SHIFT;
		return 0;
	}
/* Scroll Lock, Num Lock, and Caps Lock set the LEDs. These keys
	have on-off (toggle or XOR) action, instead of momentary action */
	if(key == RAW1_SCROLL_LOCK)
	{
		kbd_status ^= KBD_META_SCRL;
		goto LEDS;
	}
	if(key == RAW1_NUM_LOCK)
	{
		kbd_status ^= KBD_META_NUM;
		goto LEDS;
	}
	if(key == RAW1_CAPS_LOCK)
	{
		kbd_status ^= KBD_META_CAPS;
		LEDS:		
		write_kbd(0x60, 0xED);	/* "set LEDs" command */
		temp = 0;
		if(kbd_status & KBD_META_SCRL)
			temp |= 1;
		if(kbd_status & KBD_META_NUM)
			temp |= 2;
		if(kbd_status & KBD_META_CAPS)
			temp |= 4;
		write_kbd(0x60, temp);	/* bottom 3 bits set LEDs */
		return 0;
	}
	/* ignore invalid scan codes */
	//if(key >= sizeof(set1_map) / sizeof(set1_map[0]))
	//	return 0;
	/* convert raw scancode in key to unshifted ASCII in temp */
	temp = kbdus[key];
	/* defective keyboard? non-US keyboard? more than 104 keys? */
	if(temp == 0)
		return temp;
	/* handle the three-finger salute */
	if((kbd_status & KBD_META_CTRL) && (kbd_status & KBD_META_ALT) && (temp == KEY_DEL))
	{
		puts("Just press the power button.");
	}
	if(kbd_status & KBD_META_SHIFT)
		is_shift=1;
	else
		is_shift=0;
	/* I really don't know what to do yet with Alt, Ctrl, etc. -- punt */
	return temp;
}

void kb_handler(registers_t *regs)
{
  unsigned char scancode;
  int01_flag=1;
  /* Read from the keyboard's data buffer */
  scancode = inb(0x60);
  unsigned temp;
  cli();
  do
  {
    temp = inb(0x64);
    if((temp&0x01) != 0)
    {
      (void)inb(0x64);
      continue;
    }
  } while((temp&0x02) != 0);
  /* If the top bit of the byte we read from the keyboard is
  *  set, that means that a key has just been released */
  convert(scancode);
  if (scancode & 0x80)
  {
       
  }
  else
  {
    if(!is_shift){
      putc(kbdus[scancode]);
      int i = strlen(kbuf.read);
      int n = strlen(kbuf.write);
      if(i!=0 && n!=0){
        kbuf.read[i+1] = kbdus[ scancode ];
        kbuf.write[n+1] = kbuf.read[i+1];
      }else{
        kbuf.write[0] = kbdus[ scancode ];
        kbuf.read[0] = kbuf.write[0];
      }
    }else{
      putc(kbduss[scancode]);
      int i = strlen(kbuf.read);
      int n = strlen(kbuf.write);
      if(i!=0 && n!=0){
        kbuf.read[i+1] = kbduss[ scancode ];
        kbuf.write[n+1] = kbuf.read[i+1];
      }else{
        kbuf.write[0] = kbduss[ scancode ];
        kbuf.read[0] = kbuf.write[0];
      }
    }
  }
}

void install_kb()
{
  register_interrupt_handler(IRQ1, &kb_handler);
  unsigned temp;
  do
  {
    temp = inb(0x64);
    if((temp&0x01) != 0)
    {
      (void)inb(0x64);
      continue;
    }
  } while((temp&0x02) != 0);
}

