#include "Common.h"
#include "Video.h"
#include "ia32.h"
#include "pchw.h"

extern "C" void WriteIoWord(uint16_t Port, uint16_t Value);

static struct
{
	uint32_t Unicode;
	char IbmText;
} TextModeConversionTable[128] =
	{
		{0x83, 159},			// gulden sign 
		{0xa1, 173},			// inverted exclamation mark
		{0xa2, 155},			// dollar cent sign
		{0xa3, 156},			// pound sign
		{0xa5, 157},			// yen sign
		{0xab, 174},			// left pointing double angle quotation mark
		{0xb1, 241},			// plus-minus sign
		{0xb2, 253},			// superscript 2
		{0xb5, 230},			// micro sign (mu)
		{0xb7, 250},			// middle dot
		{0xba, 248},			// degree sign
		{0xbb, 175},			// right pointing double angle quotation mark
		{0xbc, 172},			// 1/4 sign
		{0xbd, 171},			// 1/2 sign
		{0xbf, 168},			// inverted question mark
		{0xc4, 142},			// capital A diaeresis
		{0xc5, 143},			// capital A ring
		{0xc6, 146},			// capital AE ligature
		{0xc9, 144},			// capital E acute
		{0xd1, 165},			// capital N tilda
		{0xd6, 153},			// capital O diaeresis
		{0xdc, 154},			// capital U diaeresis
		{0xe0, 133},			// small a grave
		{0xe1, 160},			// small a acute
		{0xe2, 131},			// small a circumflex
		{0xe4, 132},			// small a diaeresis
		{0xe5, 134},			// small a ring
		{0xe6, 145},			// small ae ligature
		{0xe7, 135},			// small c cedilla
		{0xe8, 138},			// small e grave
		{0xe9, 130},			// small e acute
		{0xea, 136},			// small e circumflex
		{0xeb, 137},			// small e diaeresis
		{0xec, 141},			// small i grave
		{0xed, 161},			// small i acute
		{0xee, 140},			// small i circumflex
		{0xef, 139},			// small i diaeresis
		{0xf1, 164},			// small n tilda
		{0xf2, 149},			// small o grave
		{0xf3, 162},			// small o acute
		{0xf4, 147},			// small o circumflex
		{0xf6, 148},			// small o diaeresis
		{0xf9, 151},			// small u grave
		{0xfa, 163},			// small u acute
		{0xfb, 150},			// small u circumflex
		{0xfc, 129},			// small u diaeresis
		{0x133,152},			// small ij ligature
		// TODO: greek
		{0x00}					// EOT
	};


CVideo::CVideo()
{
	pVideoMemory = (char*)0xb8000;

	Rows = 25;
	Columns = 80;

	CurrentX = 0;
	CurrentY = 0;

	TextColor = 7;

	OutputHex = false;

	VesaActive = false;
}


// static
CVideo* CVideo::CreateInstance()
{
	static CVideo* pVideo = NULL;

	if (pVideo == NULL)
	{
		pVideo = new CVideo;
	}

	return pVideo;
}


/*
void CVideo::PrintDiagnostics()
{
	//VesaDriver.WriteCommand(0, 0xb0c0);
	WriteIoWord(0x01ce, 0);
	*this << "id:" << hex << ReadIoWord(0x01cf) << newline;
}
*/

void CVideo::PrintChar(char Character)
{
	if (Character == '\n')
	{
		CurrentX = 0;
		CurrentY++;
	}
	else
	{
		if (!VesaActive)
		{
			pVideoMemory[CurrentX * 2 + CurrentY * 2 * Columns] = Character;
			pVideoMemory[CurrentX * 2 + CurrentY * 2 * Columns + 1] = TextColor;
		}
		else
		{
			VesaDriver.OutputCharacter(CurrentX, CurrentY, Character, TextColor);
		}

		CurrentX++;

		if (CurrentX >= Columns)
		{
			CurrentX = 0;

			CurrentY++;
		}
	}

	if (CurrentY >= Rows)
	{
		CurrentY = Rows - 1;

		if (!VesaActive)
		{
			MoveScreenOneRow();
		}
		else
		{
			VesaDriver.ScrollUp(1);
		}
	}
}

static char ConvertToIbm(uint32_t Unicode)
{
	// simple linear search for now

	for (int i = 0; TextModeConversionTable[i].Unicode != 0; i++)
	{
		if (TextModeConversionTable[i].Unicode == Unicode)
		{
			return TextModeConversionTable[i].IbmText;
		}
	}

	return '?';
}

void CVideo::PrintString(const char* pString)
{
	while (*pString != 0)
	{
		uint8_t c = *pString;
		uint32_t c32;

		if (c < 0x80)		// 1-byte character (ASCII)
		{
			PrintChar(c);
		}
		else				// multi-byte character
		{
			switch (c & 0xf0)
			{
				case 0xc0:		// 2-byte character
				case 0xd0:
					if ((pString[1] & 0xc0) == 0x80)
					{
						c32 = ((c & 0x1f) << 6) | (pString[1] & 0x3f);
						pString++;
					}
					else		// error
					{
						c32 = '?';
					}
					break;

				case 0xe0:		// 3-byte character
					if ((pString[1] & 0xc0) == 0x80 && (pString[2] & 0xc0) == 0x80)
					{
						c32 = ((c & 0x0f) << 12) | ((pString[1] & 0x3f) << 6) | (pString[2] & 0x3f);
						pString += 2;
					}
					else		// error
					{
						c32 = '?';
					}
					break;

				case 0xf0:		// 4-byte character
					if ((c & 0x08) == 0 && (pString[1] & 0xc0) == 0x80 && (pString[2] & 0xc0) == 0x80 && (pString[3] & 0xc0) == 0x80)
					{
						c32 = ((c & 0x07) << 18) | ((pString[1] & 0x3f) << 12) | ((pString[2] & 0x3f) << 6) | (pString[3] & 0x3f);
						pString += 3;
					}
					else		// error
					{
						c32 = '?';
					}
					break;

				default:		// error
					c32 = '?';
					break;
			}

			PrintChar (ConvertToIbm(c32));
		}

		pString++;
	}
}

void CVideo::MoveScreenOneRow()
{
	// TODO: use MemCopy
	for (int i = 0; i < (Rows - 1) * Columns * 2; i++)
	{
		pVideoMemory[i] = pVideoMemory[i + Columns * 2];
	}

	for (int i = 0; i < Columns; i++)
	{
		pVideoMemory[(Rows - 1) * Columns * 2 + i * 2] = ' ';
		pVideoMemory[(Rows - 1) * Columns * 2 + i * 2 + 1] = TextColor;
	}
}

/*
void CVideo::PrintHex(uint32_t Number)
{
	char HexString[17] = "0123456789ABCDEF";

	for (int i = 0; i < 8; i++)
	{
		uint32_t Temp = (Number >> 28) & 0xF;

		PrintChar(HexString[Temp]);

		Number <<= 4;
	}
}
*/

void CVideo::PrintInteger(uint32_t Number)
{
	PrintInteger(Number, 10, 1);
}

void CVideo::PrintHex(uint32_t Number)
{
	PrintInteger(Number, 16, 8);
}

void CVideo::PrintInteger(uint32_t Number, int Base, int MinLength)
{
	char TempBuffer[32];
	int Pos = 0;

	do
	{
		int Digit = Number % Base;

		if (Digit < 10)
			TempBuffer[Pos] = '0' + Digit;
		else
			TempBuffer[Pos] = 'A' + Digit - 10;

		Pos++;

		Number /= Base;
	}
	while (Number > 0);

	// Print some padding
	for (int i = Pos; i < MinLength; i++)
	{
		PrintChar('0');
	}

	for (int i = Pos - 1; i >= 0; i--)
	{
		PrintChar(TempBuffer[i]);
	}
}


void CVideo::NewLine()
{
	PrintString("\n");
}

CVideo& CVideo::operator<<(uint32_t Value)
{
	if (OutputHex)
	{
		PrintHex(Value);
	}
	else
	{
		PrintInteger(Value);
	}

	OutputHex = false;
	return *this;
}

CVideo& CVideo::operator<<(const char *pString)
{
	PrintString(pString);
	OutputHex = false;
	return *this;
}

CVideo& CVideo::operator<<(CtrlChar_t CtrlChar)
{
	switch (CtrlChar)
	{
		case newline:
			NewLine();
			break;

		case hex:
			OutputHex = true;
			break;
	}

	return *this;
}

CVideo& CVideo::operator<<(void* pAddress)
{
	PrintHex((int)pAddress);

	return *this;
}

void CVideo::CVesaDriver::SetVideoMode(unsigned short width, unsigned short height, unsigned short depth)
{
   WriteCommand(VBE_DISPI_INDEX_ENABLE, VBE_DISPI_DISABLED);
   WriteCommand(VBE_DISPI_INDEX_XRES, width);
   WriteCommand(VBE_DISPI_INDEX_YRES, height);
   WriteCommand(VBE_DISPI_INDEX_BPP, depth);
   WriteCommand(VBE_DISPI_INDEX_ENABLE, VBE_DISPI_ENABLED | VBE_DISPI_LFB_ENABLED );
}

void CVideo::CVesaDriver::ExitVideoMode()
{
   WriteCommand(VBE_DISPI_INDEX_ENABLE, VBE_DISPI_DISABLED);
}

void CVideo::CVesaDriver::WriteCommand(unsigned short index, unsigned short value)
{
   WriteIoWord(VBE_DISPI_IOPORT_INDEX, index);
   WriteIoWord(VBE_DISPI_IOPORT_DATA, value);
} 


void CVideo::CVesaDriver::OutputCharacter(int X, int Y, char Character, int Color)
{
	uint8_t* pCharData = m_pFontData + Character * m_FontHeight;
	uint8_t* pVidMem = (uint8_t*)0xE0000000 + Y * 640 * 3 * m_FontHeight + X * 8 * 3;		// TODO: remember screen dx/dy/depth

	for (int y = 0; y < m_FontHeight; y++)
	{
		for (int x = 0; x < 8; x++)
		{
			if (pCharData[y] & (1 << (7-x)))
			{
				pVidMem[(y*640+x)*3+0] = 0xff;
				pVidMem[(y*640+x)*3+1] = 0xff;
				pVidMem[(y*640+x)*3+2] = 0xff;
			}
			/*
			else
			{
				pVidMem[(y*640+x)*3+0] = 0;
				pVidMem[(y*640+x)*3+1] = 0;
				pVidMem[(y*640+x)*3+2] = 0;
			}
			*/
		}
	}
}

void CVideo::CVesaDriver::ScrollUp(int NumRows)
{
	;
}

void CVideo::SetLineHeight(int LineHeight)
{
	WriteIoByte(CVGA_CRTC_ADDR, CVGA_CRTC_IDX_MAXSCANLINE);
	uint8_t OrgVal = ReadIoByte(CVGA_CRTC_DATA);
	uint8_t NewVal = (OrgVal & 0xe0) | ((LineHeight & 0x1f) - 1);
	//*this << LineHeight << " " << hex << OrgVal << " " << hex << NewVal << newline;
	
	WriteIoByte(CVGA_CRTC_DATA, NewVal);
}


void CVideo::SetFont(uint8_t *pFontData, int LineHeight)
{
	if (!VesaActive)
	{
		WriteIoByte(CVGA_SEQ_ADDR, CVGA_SEQ_IDX_MAPMASK);
		WriteIoByte(CVGA_SEQ_DATA, 4);	// plane 2

		WriteIoByte(CVGA_GFX_ADDR, CVGA_GFX_IDX_MISC); 
		uint8_t OrgVal = ReadIoByte(CVGA_GFX_DATA);
		WriteIoByte(CVGA_GFX_DATA, 0); 		// disable odd/even

		uint8_t* pVidMem = (uint8_t*)0xa0000;

		for (int i = 0; i < 256; i++)
		{
			for (int j = 0; j < LineHeight; j++)
			{
				pVidMem[j] = pFontData[i*8+j];
			}

			pVidMem += 32;
		}

		WriteIoByte(CVGA_SEQ_DATA, 3);	// planes 0 and 1
		WriteIoByte(CVGA_GFX_DATA, OrgVal);

		SetLineHeight (LineHeight);
	}
	else
	{
		VesaDriver.SetFont(pFontData, LineHeight);
	}

	Rows = 400 / LineHeight;
}


// from PolyPlayer sources :)
void CVideo::Set90x60()
{
	if (!VesaActive)
	{
		uint32_t Regs[] = {0x6900, 0x5901, 0x5a02, 0x8c03, 0x5e04, 0x8a05, 0x0b06, 0x3e07, 0x4709, 0xea10, 0x8c11, 0xdf12, 0x2d13, 0xe715, 0x0416};

		WriteIoWord(0x3c4, 0x100);
		WriteIoByte(0x3c2, 0xe7);
		WriteIoWord(0x3c4, 0x0300);
		WriteIoWord(0x3c4, 0x0000);
		WriteIoWord(0x3c4, 0x0101);
		WriteIoWord(0x3c4, 0x0300);
		WriteIoWord(0x3d4, 0x0e11);

		for (int i = 0; i < 15; i++)
		{
			WriteIoWord(0x3d4, Regs[i]);
		}

		ReadIoByte(0x3da);
		WriteIoByte(0x3c0, 0x33);
		WriteIoByte(0x3c0, 0x00);
	}

	Columns = 90;
	Rows = 60;
}


