#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import gi

gi.require_version("Gimp", "3.0")
from gi.repository import Gimp, GLib


def _(message):
    return GLib.dgettext(None, message)


class FilmEmulation(Gimp.PlugIn):
    def do_query_procedures(self):
        return ["plug-in-film-emulation"]

    def do_create_procedure(self, name):
        procedure = Gimp.ImageProcedure.new(
            self,
            name,
            Gimp.PDBProcType.PLUGIN,
            self.run,
            None,
        )
        procedure.set_image_types("RGB*")
        procedure.set_sensitivity_mask(Gimp.ProcedureSensitivityMask.DRAWABLE)
        procedure.set_menu_label(_("Film Emulation Effect"))
        procedure.add_menu_path("<Image>/Bulevardi/")
        procedure.set_documentation("Create a false-color film effect on duplicate layers. One replicates the Harman Switch Azure. Another one replicates the Kodak Aerochrome",name)
        procedure.set_attribution("Bulevardi","Bulevardi","2026")
        return procedure

    def run(self, procedure, run_mode, image, drawables, config, run_data):
        if not drawables:
            return procedure.new_return_values(
                Gimp.PDBStatusType.CALLING_ERROR,
                GLib.Error(_("Please select an RGB layer first.")),
            )

        source = drawables[0]
        if not isinstance(source, Gimp.Layer):
            return procedure.new_return_values(
                Gimp.PDBStatusType.CALLING_ERROR,
                GLib.Error(_("Please select an image layer, not a mask or channel.")),
            )

        # One undo step for the whole operation.
        image.undo_group_start()
        try:
            # Insert the copies directly above the source layer
            # (and inside the same group, if the source is in one).
            parent = source.get_parent()
            position = image.get_item_position(source)

            # ---------------------------------------------------------
            # Layer 1: Harman Switch Azure  (red = blue & blue = red)
            # ---------------------------------------------------------
            FilmHSA = Gimp.Layer.new_from_drawable(source, image)
            FilmHSA.set_name("Harman Switch Azure")
            image.insert_layer(FilmHSA, parent, position)

            channel_filter = Gimp.DrawableFilter.new(
                FilmHSA,
                "gegl:channel-mixer",
                "Harman Switch Azure Film Channel Mixer",
            )
            channel_filter.set_blend_mode(Gimp.LayerMode.REPLACE)
            channel_filter.set_opacity(1.0)

            cfg = channel_filter.get_config()
            cfg.set_property("preserve-luminosity", False)
            # Output Red   = Blue
            cfg.set_property("rr-gain", 0.0)
            cfg.set_property("rg-gain", 0.0)
            cfg.set_property("rb-gain", 1.0)
            # Output Green = Green
            cfg.set_property("gr-gain", 0.0)
            cfg.set_property("gg-gain", 1.0)
            cfg.set_property("gb-gain", 0.0)
            # Output Blue  = Red
            cfg.set_property("br-gain", 1.0)
            cfg.set_property("bg-gain", 0.0)
            cfg.set_property("bb-gain", 0.0)

            channel_filter.update()
            FilmHSA.append_filter(channel_filter)

            # ---------------------------------------------------------
            # Layer 2: Kodak Aerochrome (hue-180°rotated copy of the ORIGINAL layer)
            # ---------------------------------------------------------
            FilmKA = Gimp.Layer.new_from_drawable(FilmHSA, image)
            FilmKA.set_name("Kodak Aerochrome")
            # Same position again: the new layer goes above "Infrared Film".
            image.insert_layer(FilmKA, parent, position)

            hue_filter = Gimp.DrawableFilter.new(
                FilmKA,
                "gimp:hue-saturation",
                "Hue 180 degrees",
            )
            hue_filter.set_blend_mode(Gimp.LayerMode.REPLACE)
            hue_filter.set_opacity(1.0)

            hue_cfg = hue_filter.get_config()
            # gimp:hue-saturation (the same operation as Colors > Hue-Saturation)
            # uses a normalized hue range in GIMP 3.2 (+1.0 = 180 degrees).
            hue_pspec = hue_cfg.find_property("hue")
            hue_value = getattr(hue_pspec, "maximum", 1.0)
            hue_cfg.set_property("hue", hue_value)

            hue_filter.update()
            FilmKA.append_filter(hue_filter)

            image.set_selected_layers([FilmKA])

        except Exception as exc:
            return procedure.new_return_values(
                Gimp.PDBStatusType.EXECUTION_ERROR,
                GLib.Error(str(exc)),
            )
        finally:
            image.undo_group_end()

        Gimp.displays_flush()
        return procedure.new_return_values(
            Gimp.PDBStatusType.SUCCESS,
            GLib.Error(),
        )


Gimp.main(FilmEmulation.__gtype__, sys.argv)
