#include "udpl_dll_imp.h"
#include "sn76489a.h"
#include "command_list.h"


// ***********************************************************************************************
// SN76489A
// ***********************************************************************************************
uint8_t DCSG_INIT_REGISTER[][2] = {
	{ 0x00, 0x9f },	// 1 mute
	{ 0x00, 0xbf },	// 2 mute
	{ 0x00, 0xdf },	// 3 mute
	{ 0x00, 0xff },	// noise mute
	{ 0x00, 0xe0 },
	{ 0x00, 0x81 },
	{ 0x00, 0x00 },
	{ 0x00, 0xa1 },
	{ 0x00, 0x00 },
	{ 0x00, 0xc1 },
	{ 0x00, 0x00 }
};


bool __stdcall UdplChipSN76489A::setRegister(uint32_t addr, uint32_t data) {

	//
	// LSB と MSB の解釈が定まってなくてダメ
	//
	/*
	uint8_t len;
	uint8_t c0 = (0x01 << (addr >> 8)) | slotno_bit;
	uint8_t *p = send_command;
	
	memcpy(p, COMMAND_SET_BUS, sizeof(COMMAND_SET_BUS));
	p += sizeof(COMMAND_SET_BUS);

	*p++ = c0;

	if ((addr & 0x06) == 0x06) {	// noise
		*p++ = data | (addr << 4) | 0x80;
		*p++ = wait32;
		len = COMMAND_SET_BUS[0] + 1;
	}
	else {
		*p++ = (data >> 6) | (addr << 4) | 0x80;
		*p++ = wait32;

		memcpy(p, COMMAND_SET_BUS, sizeof(COMMAND_SET_BUS));
		p += sizeof(COMMAND_SET_BUS);
		*p++ = c0;
		*p++ = (data << 2) & 0xff;
		*p++ = wait32;
		len = (COMMAND_SET_BUS[0] << 1 )+ 2;
	}
	psockIf->pushData(send_command, len);
	*/
	return true;
}

bool __stdcall UdplChipSN76489A::writeBus(uint8_t abit, uint8_t data)
{
	uint8_t *p = send_command;
	memcpy(p, COMMAND_SET_BUS, sizeof(COMMAND_SET_BUS));
	p += sizeof(COMMAND_SET_BUS);
	*p++ = (abit & 0x0F) | slotno_bit;
	*p++ = data;
	*p++ = wait32;
	
	psockIf->pushData(send_command, COMMAND_SET_BUS[0] + 1);
	sendStat.store(true, std::memory_order_release);

	return true;
}

uint32_t __stdcall UdplChipSN76489A::getRegister(uint32_t addr)
{
	return 0U;
}
bool __stdcall UdplChipSN76489A::setPcmData(void *pdat)
{
	return true;
}

// アドレスウェイト、データウェイトの値の計算
void UdplChipSN76489A::setWaits(uint32_t clk)
{
	wait32 = (uint8_t)((32.0f * 1000000 / (float)clk) + 0.99f);
};

void UdplChipSN76489A::initRegs(void)
{
	unsigned int sum = 0;
	for (unsigned int i = 0; i < _countof(DCSG_INIT_REGISTER); ++i) {
		writeBus(DCSG_INIT_REGISTER[i][0], DCSG_INIT_REGISTER[i][1]);
		sum += COMMAND_SET_BUS[0] + 1;
		if (sum > max_send_size) {	// でかい
			psockIf->waitBufClear();
			sum = 0;
		}
	}
}