#! /usr/bin/env python

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 GLib
from gi.repository import GObject
from gi.repository import Gio
import os

class ExportPngClose(Gimp.PlugIn):

    def do_query_procedures(self):
        return ['python-fu-exportPngClose']

    def do_create_procedure(self, name):

        procedure = Gimp.ImageProcedure.new(
          self, name, Gimp.PDBProcType.PLUGIN, self.run, None)
        procedure.set_image_types('*')
        procedure.set_documentation(
          'Saves file to e:\\scans\\inpic\\puzzle\\done\new\#.png','It then closes the image.',)
        procedure.set_menu_label('_ExportPngClose...')
        procedure.add_menu_path('<Image>/File')
        procedure.set_attribution('Leonard', 'Leonard', '2025')
        return procedure
#class ExportPngClose(Gimp.PlugIn):
    def run(self, procedure, run_mode, image, n_drawables, drawables, args):
        if image is None:
            Gimp.message('no image')
            return Gimp.ValueArray.new(GLib.Value(Gimp.PDBStatusType.CALL_ERROR, None))
        # Get the original image filename
        imagefile = image.get_file()
        original_filepath = imagefile.get_path()
        if not original_filepath:
            # Handle images that haven't been saved yet (optional: prompt user or return error)
            print("Image has no filename. Please save the original file first.")
            return Gimp.ValueArray.new(GLib.Value(Gimp.PDBStatusType.CALL_ERROR, None))
        # Use pathlib to easily handle path components
        original_path, filenamex = os.path.split(original_filepath)
        new_filename = os.path.splitext(filenamex)[0] + '.png'
        full_export_path = os.path.join("e:\\scans\\inpic\\puzzle\\done\\new", new_filename)
        Gimp.message('fnex='+full_export_path)
        # Get the active drawable (layer/channel) for saving
#       drawable = image.get_active_drawable()
        drawable = image.get_selected_drawables()
        # file_png_save requires a Gio.File object for GIMP 3.x
        export_file = Gio.File.new_for_path(str(full_export_path))
        Gimp.message('export file')
        # The arguments for file_png_save are extensive. Using file-png-save-defaults is simpler if defaults are fine.
        # Alternatively, use the specific function with full arguments:
        Gimp.file_png_save(
            image,                      # image: The GIMP image object
            drawable,                   # drawable: The layer to save (e.g., image.layers[0])
#            export_file,                # filename: Full path to the output file
            str(full_export_path),      # raw_filename (unused for PNG): Same as filename
            str(full_export_path),      # raw_filename (unused for PNG): Same as filename
            9,                          # compression: 0 (none) to 9 (max)
            0,                          # interlacing: 0 (no) or 1 (yes)
            0,0,0,                      # bkgnd_r, bkgnd_g, bkgnd_b: Background color (for transparent images)
            0,                          # save_bkgnd: 0 (no), 1 (yes)
            0,                          # save_gamma: 0 (no), 1 (yes)
            0,                          # save_interlace: 0 (no), 1 (yes)
            0                           # save_timestamp: 0 (no), 1 (yes)
        )
#           pdb_procedure="file-png-save", # Internal use, can be placeholder
#           run_mode=Gimp.RunMode.NONINTERACTIVE,
        Gimp.message('png saved')
        # Close the image display/window
        # Find all displays associated with the image and close them
        displays = image.get_displays()
        for display in displays:
            Gimp.Display.quit(display)
        # The image will be closed automatically when the last display is closed and no more references exist.
        return Gimp.ValueArray.new(GLib.Value(Gimp.PDBStatusType.SUCCESS, None))

Gimp.main(ExportPngClose.__gtype__, sys.argv)
