// hc08gpioport.cpp
//
// Copyright (C) 2016 - salvi
//
// 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 2 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/>.

#define CURSES_H
#include <curses.h>
#include "displaylcd.h"
#include "hc08gpioport.h"
#ifndef HCIWINDOW_H
#include "hcwindow.h"
#endif
#include "log.h"

/*
 *  DISPLAY:
 *  DB4       15          PTB0
 *  DB5       14          PTB1
 *  DB6       11          PTB2
 *  DB7       10          PTB3
 *
 *  EN_LCD    3           PTB6                LED Verde
 *  RS_LCD    5           PTA4/OSC2/AD2/KBI4  LED Giallo
 * 
 *  PTB7        S5
 * 
 * 
 */

#define S5PIN		0x80
#define YELLOWLED   0x10
#define GREENLED	0x40

unsigned char GpIoPort::evalOutput() {
  unsigned char  v;
  v = value & ddr | (~ddr & pue);
  for (InputConnector *in = inputs; in; in = in -> getNext()) {
	v = in->add(v);
  }
  return v;
}

unsigned char GpIoPort::getValue(unsigned int rAddress) {
	switch (rAddress - address) {
		case 0 :
			return evalOutput();
		case DDROFFSET:
			return ddr;
		case PUEOFFSET:
			return pue;
		default:
			return 0xff;
	}
}

unsigned char GpIoPort::getRowValue(unsigned int rAddress) {
	switch (rAddress - address) {
		case 0 :
			return value;
		case DDROFFSET:
			return ddr;
		case PUEOFFSET:
			return pue;
		default:
			return 0xff;
	}
}

void GpIoPort::sentToOutput() {
  unsigned char v = evalOutput();
  // Log::printf("GpIoPort::sendToOutput %04x %02x (%02x - %02x -> %02x)", address, value, ddr, pue, (value & ddr) | pue);
  for (OutputConnector *out = outputs; out; out = out -> getNext()) {
	out->out(v);
  }
}

void GpIoPort::setValue(unsigned int rAddress, unsigned char dato) {
	switch (rAddress - address) {
		case 0 :
			value = dato;
			sentToOutput();
			break;
		case DDROFFSET:
			ddr = dato;
			sentToOutput();
			break;
		case PUEOFFSET:
			pue = dato;
			break;
	}
}
