#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#   GIMP - The GNU Image Manipulation Program
#   Copyright (C) 1995 Spencer Kimball and Peter Mattis
#
#   Layer merge and RGB composition for uneven yellowed photo correction
#                                           for GIMP3 Ver. 1.1
#   Copyright (C) 2021-25 Ohnishi, Yasuo
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <https://www.gnu.org/licenses/>.

import sys, os
import gi
gi.require_version('Gimp', '3.0')
from gi.repository import Gimp
gi.require_version('GimpUi', '3.0')
from gi.repository import GimpUi

from gi.repository import Gtk, GLib, Gegl, GObject, Gio


class layer_merge_and_rgb_combine_g3 (Gimp.PlugIn):
    def do_query_procedures(self):
        return [ "py-plug-in-yimgcorr-layer-merge-and-rgb-combine" ]

    def do_set_i18n (self, name):
        return False

    def do_create_procedure(self, name):
        procedure = Gimp.ImageProcedure.new(self, name,
                                            Gimp.PDBProcType.PLUGIN,
                                            self.run, None)

        procedure.set_image_types("*")

        procedure.set_menu_label("新B画像作成→RGB合成...")
        procedure.add_menu_path('<Image>/My_Plugins/黄変写真補正ツール/')

        procedure.set_documentation("再建B画像を作成しRGB合成を行う",
                                    "make_B_image_and_compose_RGB",
                                    name)
        procedure.set_attribution("Ohnishi, Yasuo", "Ohnishi, Yasuo", "(c) 2021-25")
        return procedure

    def run(self, procedure, run_mode, image, drawables, config, run_data):
        GimpUi.init("Python-layer_merge_and_rgb_combine_g3.py")
        #  delete currect selections
        Gimp.Selection.none(image)
        #   transform visible image to new layer
        new_layer = Gimp.Layer.new_from_visible(image, image, "New B")
            # add new layer as 3rd layer (New B)
        image.insert_layer(new_layer, None, 2)
    #   get currect image filename to "filename"
        filename = image.get_file().get_path()
        Gimp.message(filename)
        ext = os.path.splitext(os.path.basename(filename))[0]
        # extract basename of filename (extension removed)

# compose R, G, B image to one New color image
        layers = image.get_layers()
        Gimp.edit_copy([layers[0]]) # convert mask image to list variable of layer
        red = Gimp.edit_paste_as_new_image()
        dispRed = Gimp.Display.new(red)
        Gimp.edit_copy([layers[1]]) # convert mask image to list variable of layer
        green = Gimp.edit_paste_as_new_image()
        dispGr = Gimp.Display.new(green)
        Gimp.edit_copy([layers[2]]) # convert mask image to list variable of layer
        blue = Gimp.edit_paste_as_new_image()
        dispBl = Gimp.Display.new(blue)

#             "img.layers[3]" & second "blue" for dummy parameters
        procedure = Gimp.get_pdb().lookup_procedure('plug-in-compose')
        config  = procedure.create_config()
        config.set_property('run-mode', Gimp.RunMode.NONINTERACTIVE)
        config.set_property('image', red)
        #config.set_property('drawables', layers[3]) #dummy
        config.set_property('image-2', green)
        config.set_property('image-3', blue)
        #config.set_property('image-4', blue) #dummy
        try:
            config.set_property('compose-type', 'RGB')
        except Exception as e:
            Gimp.message(f"❌ Cannot set compose-type properly:\n\n{e}")
        result = procedure.run(config)
        #if result.index(0) is Gimp.PDBStatusType.SUCCESS:
        compose = result.index(1)
                #The return values of PDB Procedure itself are index(1) or after
        filename = filename.replace("_RGB.xcf", "_補正1.xcf")
        Gimp.message("filename1: " + filename)
        new_file0 = Gio.File.new_for_path(filename)
        compose.set_file(new_file0)
        Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, compose, new_file0, None)
        disp = Gimp.Display.new(compose)
        filename = filename.replace("_補正1.xcf", "_補正1.tif")
        new_file1 = Gio.File.new_for_path(filename)
        Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, compose, new_file1, None)
        Gimp.message("filename2: " + filename)

        dispRed.delete()
        dispGr.delete()
        dispBl.delete()
        # do what you want to do, then, in case of success, return:
        return procedure.new_return_values(Gimp.PDBStatusType.SUCCESS, GLib.Error())


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