#include "Palette.h"

#ifdef CPC
// The initial palette defining the colours that will be used to draw the graphics in the game.
// Replacing bright magenta with white for basic transparency.
const u8 initialPalette[COLOUR_COUNT] = { 0x4, 0xb, 0x14, 0x0, 0x0, 0xa, 0xc, 0xb, 0xb, 0x15, 0x1c, 0x16, 0xe, 0x18, 0x1e, 0x12 };
#else
// The initial palette defining the colours that will be used to draw the graphics in the game.
u8 initialPalette[COLOUR_COUNT] = { 0x4, 0xb, 0x14, 0x0, 0xd, 0xa, 0xc, 0xb, 0xb, 0x15, 0x1c, 0x16, 0xe, 0x18, 0x1e, 0x12 };
#endif

// The palette defining the colours that will be used to draw the graphics in the game and is updated by interactions in the game.
u8 gamePalette[COLOUR_COUNT] = { 0x4, 0xb, 0x14, 0x0, 0xd, 0xa, 0xc, 0xb, 0xb, 0x15, 0x1c, 0x16, 0xe, 0x18, 0x1e, 0x12 };

// The type of transparency used when constructing sprites.
u8 transparencyType = 0;

void initPalette()
{
#ifdef CPC
    cpct_memcpy(gamePalette, initialPalette, COLOUR_COUNT);
#else
    memcpy(gamePalette, initialPalette, COLOUR_COUNT);
#endif

    updatePalette();
}

void switchColour(u8 beforeColour, u8 afterColour)
{
    u8 i = 0;

    // Update any occurrence of the before colour to the after colour.
    // The first 5 colours are excluded as they are to remain static otherwise the
    // game sprites will be far too messed up.
    for (i = 5; i < COLOUR_COUNT; ++i)
    {
        // The secondary white is used for the player independently of a colour switch.
        if (i == PALETTE_POSITION_BRIGHT_WHITE_2)
        {
            continue;
        }

        if (gamePalette[i] == beforeColour)
        {
            gamePalette[i] = afterColour;
        }
    }

    // Update the palette following the colour changes.
    updatePalette();
}

void switchColourByPosition(u8 beforePosition, u8 afterPosition)
{
    switchColour(gamePalette[beforePosition], gamePalette[afterPosition]);
}

void updatePalette()
{
#ifdef CPC
    cpct_setPalette(gamePalette, COLOUR_COUNT);
#else
    destroyAllAllegroSpriteSets();
    initAllAllegroSpriteSets(gamePalette, transparencyType);
#endif

    mapRedraw = TRUE;
    player.redraw = TRUE;
}
