from .std import *

N_SPI_SEG = 4

rsm_uart = 0x380
rsm_coproc = 0x322
rsm_spi = 0x342
rsm_gpio = 0x382
fai = 0x213
fai_fgl = 0
fai_fgh = 1
fai_dnl = 2
fai_dnh = 3
fai_idl = 4
fai_idh = 5
fai_aux = 6
mac = 0x214
mac_mdi = 0
mac_dly = 1
mac_cfg = 2
mac_srl = 3
mac_srh = 4
mac_dsl = 5
mac_dsh = 6
cpr = 0x215
ttl = 0x216
dio = 0x217
dio_dir = 0
dio_inv = 1
dio_pos = 2
dio_neg = 3
ctr = 0x218
csm = 0x219
tts = 0x21A
tev = 0x21B
clr = 0x21C
ena = 0x21D
opt = 0x21E
ftw = 0x21F
pow = 0x220
amp = 0x221
ofs = 0x222
sig = 0x223
iou = 0x224
cou = 0x225
iin = 0x226
cin = 0x227
spi = 0x228
spi_ctl = N_SPI_SEG
spi_cnt = spi_ctl+1

PB = lambda x,y:((x-1)<<4)|(y-1)
PC = lambda x,y:((x-1)<<4)|(y+7)
for i in range(1,13):
    globals()[f'P{i}'] = i-1
    for j in range(1,9):
        globals()[f'P{i}B{j}'] = PB(i,j)
        globals()[f'P{i}C{j}'] = PC(i,j)

def gpio(pos, out=1):
    return [sfs(cou,6+(pos>>5)),amk(cou,0x300|((1<<(pos&3))<<4)|(((pos&0x1F)>>2)<<1),0x101 if out else 0x100)]

def gpio_set(pos, val):
    return [sfs(cou,pos>>5),amk(cou,0x300|((1<<(pos&3))<<4)|(((pos&0x1F)>>2)<<1),0x101 if val else 0x100)]
gpio_on = lambda pos:gpio_set(pos,1)
gpio_off = lambda pos:gpio_set(pos,0)

def spi_config(chn, pol, pha, sdi_ltn, clk_div):
    return [sfs(spi+chn,spi_ctl),*cli(spi+chn,clk_div|(sdi_ltn<<12)|(pha<<16)|(pol<<17))]

def spi_write(chn,dat,cnt):
    code = []
    for i in range(len(dat)):
        code += [sfs(spi+chn,N_SPI_SEG-1-i),*cli(spi+chn,dat[i])]
    return code+[sfs(spi+chn,spi_cnt),*cli(spi+chn,cnt|(cnt<<10))]

def spi_wait():
    return [amk(rsm,rsm_spi,0x101),nop(H),amk(rsm,rsm_spi,0x100)]

def wr_5372(chn, mod, adr, dat):
    dat &= 0xffff
    dat |= (adr|(mod<<6))<<16
    return spi_write(chn,[dat<<8], 24)

def wr_5791(chn, rwb, adr, dat):
    dat &= 0xfffff
    dat |= (adr|(rwb<<3))<<20
    return spi_write(chn,[dat<<8],24)