/*
 * gfx_palette.c — graphics-side palette wrappers.
 *
 * The "legacy" entry points (gfx_pal_load / gfx_pal_set) keep their own
 * inline-asm implementation rather than thunking through pal_*; this
 * avoids depending on SDCC's __sdcccall(1) stack-shuffling for nested
 * calls, which empirically misbehaves here (the trampoline corrupts the
 * text palette so the next text-mode print hangs). Functionally these
 * are identical to the old gfx_core.c versions.
 *
 * The newer get / reset helpers are simple wrappers — they're either
 * not on hot paths or are first introduced here, so the thunk overhead
 * doesn't matter and we get to share the asm with libc/video/palette.c.
 */

#include <stdint.h>
#include <gfx.h>
#include <palette.h>

static uint8_t  gpl_num_;
static uint8_t  gpl_start_;
static uint8_t  gpl_count_;
static uint16_t gpl_data_;

void gfx_pal_load(uint8_t pal_num, uint8_t start, uint8_t count,
                  const uint8_t *data)
{
    gpl_num_   = pal_num;
    gpl_start_ = start;
    gpl_count_ = count;
    gpl_data_  = (uint16_t)(uintptr_t)data;

    __asm
        push  ix
        ld    a, (_gpl_start_)
        ld    e, a                  ; E = start
        ld    a, (_gpl_count_)
        ld    d, a                  ; D = count (0 → 256)
        ld    hl, (_gpl_data_)      ; HL = data
        ld    b, #0xFF              ; mask
        ld    a, (_gpl_num_)        ; A = palette number
        ld    c, #0xA4              ; BIOS PIC_SET_PAL
        rst   #0x08
        pop   ix
    __endasm;
}

void gfx_pal_set(uint8_t pal_num, uint8_t idx,
                 uint8_t r, uint8_t g, uint8_t b)
{
    uint8_t entry[4];
    entry[0] = b;
    entry[1] = g;
    entry[2] = r;
    entry[3] = 0;
    gfx_pal_load(pal_num, idx, 1, entry);
}

void gfx_pal_get(uint8_t pal_num, uint8_t start, uint8_t count,
                 uint8_t *data)
{
    pal_get(pal_num, start, count, data);
}

void gfx_pal_get_color(uint8_t pal_num, uint8_t idx,
                       uint8_t *r, uint8_t *g, uint8_t *b)
{
    pal_get_color(pal_num, idx, r, g, b);
}

void gfx_pal_reset(void)
{
    pal_reset(PAL_GRAPH);
}
