#include "udpl_dll_imp.h"
#include "psg_ssg.h"
#include "command_list.h"

// **********************************************************************
// PSG
// **********************************************************************

uint32_t PSG_INIT_REGISTER[][2] = {
	{ 0x0008, 0x00 },	// PSG mute
	{ 0x0009, 0x00 },
	{ 0x000a, 0x00 },
	{ 0x0000, 0x00 },	// SSG
	{ 0x0001, 0x00 },
	{ 0x0002, 0x00 },
	{ 0x0003, 0x00 },
	{ 0x0004, 0x00 },
	{ 0x0005, 0x00 },
	{ 0x0006, 0x00 },
	{ 0x0007, 0x00 },
	{ 0x000b, 0x00 },
	{ 0x000c, 0x00 },
	{ 0x000d, 0x00 },
	{ 0x000e, 0x00 },
	{ 0x000f, 0x00 }
};


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

	bool ret = false;

	uint8_t *p = send_command;

	memcpy(p, COMMAND_SET_REG, sizeof(COMMAND_SET_REG));
	p += sizeof(COMMAND_SET_REG);

	*p++ = slotno_bit;
	*p++ = addr & 0xFF;
	*p++ = data;
	*p++ = wait0;
	*p++ = wait0;

	// 送信する
	psockIf->pushData(send_command, COMMAND_SET_REG[0] + 1);
	sendStat.store(true, std::memory_order_release);

	return true;
}
bool __stdcall UdplChipPSG::writeBus(uint8_t abit, uint8_t data)
{
	return true;
}
uint32_t __stdcall UdplChipPSG::getRegister(uint32_t addr)
{
	uint32_t ret = 0;
	uint8_t *p = send_command;
	memcpy(p, COMMAND_GET_REG, sizeof(COMMAND_GET_REG));
	p += sizeof(COMMAND_GET_REG);

	*p++ = 0x01 | slotno_bit;	// レジスタリード
	*p++ = addr & 0xff;
	*p++ = wait0;
	if (psockIf->pushRecv(send_command, COMMAND_GET_REG[0] + 1, recv_command, sizeof(recv_command))) {
		ret = recv_command[recv_command[0]];
	}

	return ret;
}
bool __stdcall UdplChipPSG::setPcmData(void *pdat)
{
	return true;
}


// アドレスウェイト、データウェイトの値の計算
void UdplChipPSG::setWaits(uint32_t clk)
{
	wait0 = 0;	// address も data も Rising edge からホールドが 100[ns]. 	
};

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