#
# Python Imaging Library
# $Id$
#
# stuff to read GIMP palette files
#
# History:
# 1997-08-23 fl     Created
# 2004-09-07 fl     Support GIMP 2.0 palette files.
#
# Copyright (c) Secret Labs AB 1997-2004.  All rights reserved.
# Copyright (c) Fredrik Lundh 1997-2004.
#
# See the README file for information on usage and redistribution.
#
from __future__ import annotations

import re
from typing import IO

from ._binary import o8


class GimpPaletteFile:
    """File handler for GIMP's palette format."""

    rawmode = "RGB"

    def __init__(self, fp: IO[bytes]) -> None:
        if not fp.readline().startswith(b"GIMP Palette"):
            msg = "not a GIMP palette file"
            raise SyntaxError(msg)

        palette: list[int] = []
        for i in range(256):
            s = fp.readline()
            if not s:
                break

            # skip fields and comment lines
            if re.match(rb"\w+:|#", s):
                palette.append(o8(i) * 3)
                continue
            if len(s) > 100:
                msg = "bad palette file"
                raise SyntaxError(msg)

            v = s.split(maxsplit=3)
            if len(v) < 3:
                msg = "bad palette entry"
                raise ValueError(msg)

            palette.append(o8(int(v[0])) + o8(int(v[1])) + o8(int(v[2])))

        self.palette = b"".join(palette)

    def getpalette(self) -> tuple[bytes, str]:
        return self.palette, self.rawmode