import sys

# define palette(s) here
palettes = {
    'blues': [0x15234b, 0x29366f, 0x304ead, 0x3b5dc9, 0x4485c9, 0x41a6f6, 0x75c4f5, 0xbeeff7, 0x3c208a],
}

sweetie16 = [0x1a1c2c, 0x5d275d, 0xb13e53, 0xef7d57, 0xffcd75, 0xa7f070, 0x38b764, 0x257179, 0x29366f, 0x3b5dc9, 0x41a6f6, 0x73eff7, 0xf4f4f4, 0x94b0c2, 0x566c86, 0x333c57]

# mostly for JASC output
def intToR_G_B(intValue):
    r = (intValue >> 16) & 0xff
    g = (intValue >> 8) & 0xff
    b = intValue & 0xff
    return "%s %s %s" % (r, g, b)

# for Aseprite or whatever
def outputJasc():
    for paletteIndex in palettes:
        paletteString = "JASC-PAL\n0100\n%s\n" % len(palettes[paletteIndex])
        for color in palettes[paletteIndex]:
            paletteString += intToR_G_B(color) + "\n"

        filename = "%s.pal" % paletteIndex
        fileOut = open(filename, "w+")
        fileOut.write(paletteString)
        fileOut.close()

# only replaces entries from 4 onward by default
def outputLua(includeDecoder=False):
    paletteString = "palettes = {\n"
    for paletteIndex in palettes:
        paletteString += "\t%s = {" % paletteIndex
        for color in palettes[paletteIndex]:
            paletteString += hex(color) + ","

        paletteString += "},\n"
    paletteString += "}"

    if includeDecoder:
        paletteString += "\n"
        paletteString += "function palset(entry, val)\n\tpoke(0x3fc0+(entry*3), val//65536)\n"
        paletteString += "\tpoke(0x3fc1+(entry*3), (val//256)%256)\n\tpoke(0x3fc2+(entry*3), val%256)\n"
        paletteString += "end\n\n"
        paletteString += "function swap_palette(pal_name)\n\tfor i = 4,#palettes[pal_name]+3 do\n"
        paletteString += "\t\tpalset(i, palettes[pal_name][i-3])\n\tend\nend\n"

    filename = "palettes.lua"
    fileOut = open(filename, "w+")
    fileOut.write(paletteString)
    fileOut.close()

# output can be pasted into the TIC-80 sprite editor
# can only output a single palette, practically
# also, i am replacing really specific entries here - be aware
def outputTic(paletteName):
    paletteString = ""
    paletteCounter = 0
    for i in range(0, 16):
        if paletteCounter < 3 or paletteCounter > 11:
            paletteString += hex(sweetie16[paletteCounter]).replace('0x', '')
        else:
            color = palettes[paletteName][i - 3]
            paletteString += hex(color).replace('0x', '')
        paletteCounter += 1

    filename = "tic-%s.txt" % paletteName
    fileOut = open(filename, "w+")
    fileOut.write(paletteString)
    fileOut.close()

# parse CLI arguments and take action
if len(sys.argv) > 1:
    outFormat = sys.argv[1]
    print("Outputting %s" % outFormat)
    if outFormat == "jasc":
        outputJasc()
    if outFormat == "lua":
        outputLua(True)
    if outFormat == "tic":
        outputTic(sys.argv[2])
else:
    print("Incorrect number of arguments.")
    print("Usage: palettegen.py jasc|lua|tic [palette]")
