#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#   GIMP - The GNU Image Manipulation Program
#   Copyright (C) 1995 Spencer Kimball and Peter Mattis
#
#   Loading files for unevenly yellowed image correction for GIMP3 Ver. 3.6.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

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 load_files_y_img_corr_g3(Gimp.PlugIn):
    def do_query_procedures(self):
        return [ "py-plug-in-yimgcorr-load-files" ]

    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_sensitivity_mask(Gimp.ProcedureSensitivityMask.ALWAYS)

        procedure.set_menu_label("ファイル読込(v3.6)...")
        procedure.add_menu_path('<Image>/My_Plugins/黄変写真補正ツール/')

        procedure.set_documentation("編集素材ファイルを読込む",
                                    "loading files for unevenly yellowed image correction for GIMP 3.0",
                                    name)
        procedure.set_attribution("Ohnishi, Yasuo", "Ohnishi, Yasuo", "(c) 2021-25")

        return procedure

    def run(self, procedure, run_mode, image, drawables, config, run_data):
        dialog = Gtk.FileChooserDialog(
            title="作成元黄変写真ファイルの指定",
            parent=None,
            action=Gtk.FileChooserAction.OPEN,
            buttons=("_キャンセル", Gtk.ResponseType.CANCEL, "_開く", Gtk.ResponseType.OK)
            )
        #dialog.add_buttons("_キャンセル", Gtk.ResponseType.CANCEL, "_開く", Gtk.ResponseType.APPLY)
        dialog.set_position(Gtk.WindowPosition.CENTER)  # Center the dialog
        dialog.set_default_size(400, 300)
        dialog.set_resizable(True)
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            DoProcess = True
            imgfname = dialog.get_filename()
        else:
            DoProcess = False
        dialog.hide()
        dialog.destroy()
        if DoProcess == True:
            # load mask image file
            #imgfname = dialog.get_filename()
            Gimp.message(imgfname)
            filenames = [imgfname + "_Fg_Mask_Yrsv.tif",
                imgfname + "_Brown_Adjst_Mask.tif",
                imgfname + "_Green_Adjst_Mask.tif",
                imgfname + "_Shadow_Mask.tif",
                imgfname + "_Periph_Adjst_Mask.tif",
                imgfname + "_Bg_Thld_Mask.tif",
                imgfname + "_Fg_Mask.tif",
                imgfname + "_B.tif",
                imgfname + "_B_Fg.tif",
                imgfname + "_Periph_Adjst.tif",
                imgfname + "_Brown_Adjst.tif", # > Brown_Adjst_Mg_cast
                imgfname + "_B.tif", # > Brown_Adjst
                imgfname + "_Green_Adjst.tif",
                imgfname + "_B_Bg.tif",
                imgfname + "_Shadow.tif",
                imgfname + "_G.tif",
                imgfname + "_R.tif"]

            image = Gimp.file_load(Gimp.RunMode.NONINTERACTIVE, \
                                   Gio.File.new_for_path(imgfname))
            #change image's file name
            imgfnameRGB = imgfname  + "_RGB.xcf"
            image.set_file(Gio.File.new_for_path(imgfnameRGB))
            #display loaded file
            disp = Gimp.Display.new(image)
            Gimp.message(str(len(filenames)))
            for filename in filenames:
                try: # insert loaded file image as layer
                    new_layer = Gimp.file_load_layers\
                        (run_mode, image, Gio.File.new_for_path(filename))
                    image.insert_layer(new_layer[0], None, 0)
                    new_layer[0].add_alpha()
                except Exception as e:
                    Gimp.message(f"Error:\n\n{e}")
            layers = image.get_layers()
            # make some layers unvisible
            layers[0].set_visible(False) # R
            layers[1].set_visible(False) # G
            layers[5].set_visible(False) # Brown_Adjst
            for i in range(10, 17): # make mask images unvisible
                layers[i].set_visible(False)
            #   set layer names
            layers[0].set_name("R")
            layers[1].set_name("G")
            layers[2].set_name("Shadow")
            layers[7].set_name("Periph_Adjst")
            layers[3].set_name("B_Bg")
            layers[4].set_name("Green_Adjst")
            layers[5].set_name("Brown_Adjst")
            layers[6].set_name("Brown_Adjst_Mg_cast")
            layers[8].set_name("B_Fg")
            layers[9].set_name("B")
            layers[10].set_name("Fg_Mask")
            layers[11].set_name("Bg_Mask")
            layers[12].set_name("Periph_Adjst_Mask")
            layers[13].set_name("Shadow_Mask")
            layers[14].set_name("Green_Adjst_Mask")
            layers[15].set_name("Brown_Adjst_Mask")
            layers[16].set_name("Fg_Mask_Yrsv")
            self.apply_mask2layer(10, 8, layers, image) # Copy Fg Mask Image to Layer
            self.apply_mask2layer(11, 3, layers, image) # Copy Bg Mask Image to Layer
            self.apply_mask2layer(12, 7, layers, image) # Copy Periph Mask Image to Layer
            self.apply_mask2layer(13, 2, layers, image) # Copy Shadow Mask Image to Layer
            self.apply_mask2layer(14, 4, layers, image) # Copy Green Adjst Mask Image to Layer
            self.apply_mask2layer(15, 6, layers, image) # Copy Brown Adjst Mask Image to Layer
            self.apply_mask2layer(15, 5, layers, image) # Copy Brown Adjst Mask Image to Layer(2nd)

            # Back Ground Layer (image.layers[17]) to White
            color = Gegl.Color.new("#FFFFFF") #input color number hex format
            Gimp.context_set_background(color) #Set background painting color
        #    Fill layer[17] with Background Painting Color
            layers[17].edit_fill(Gimp.FillType.BACKGROUND)
        else: # dialog canceled
            return  procedure.new_return_values(Gimp.PDBStatusType.CANCEL, GLib.Error())
        # do what you want to do, then, in case of success, return:
        return procedure.new_return_values(Gimp.PDBStatusType.SUCCESS, GLib.Error())

    def apply_mask2layer(self, n_mask, n_layer, layers, image):
        copyed_layer = [layers[n_mask]] # convert mask image to list variable of layer
        Gimp.edit_copy(copyed_layer)
            # Copy mask image as list v. of layer(s) even if only one image exits.
        target_layer =  layers[n_layer] # Get target layer
        # add mask to the target layer
        mask = target_layer.create_mask(Gimp.AddMaskType.WHITE)
        target_layer.add_mask(mask)
        target_layer.set_edit_mask(True)
        Gimp.edit_paste(mask, False) # paste mask image to mask
        Gimp.floating_sel_anchor(image.get_floating_sel()) #get floating_sel as layer!
        target_layer.set_edit_mask(False)


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