#!/usr/bin/env python3

import gi
gi.require_version('Gimp', '3.0')
from gi.repository import Gimp
gi.require_version('GimpUi', '3.0')
from gi.repository import GLib
from gi.repository import Gio
import os
import sys
import datetime
import configparser

class PrintFabExportPng(Gimp.PlugIn):
    __gproperties__ = {}

    def do_query_procedures(self):
        return ['printfab-export-png']
    
    def do_set_i18n (self, name):
        return False

    def do_create_procedure(self, name):
        if name == 'printfab-export-png':
            procedure = Gimp.ImageProcedure.new(
                self,
                name,
                Gimp.PDBProcType.PLUGIN,
                self.run,
                None
            )
            lang = os.getenv('LANG', 'en_EN.UTF-8')
            if lang == 'de_DE.UTF-8':
                procedure.set_menu_label('An TurboPrint senden')
            else:
                procedure.set_menu_label('Send to TurboPrint')
            procedure.set_attribution("ZEDOnet", "ZEDOnet", "2025 Version 3.0")
            procedure.set_documentation(
                'Send current image to PrintFab',
                None,
                name
            )
            procedure.add_menu_path('<Image>/File/[Send]')

            return procedure

    def run(self, procedure, run_mode, image, drawables, config, run_data):        
        temp_image = image.duplicate()

        # temp_image.flatten()
        temp_image.merge_visible_layers(Gimp.MergeType.CLIP_TO_IMAGE)
        
        allowed_precisions = {
            Gimp.Precision.U8_NON_LINEAR,
            #Gimp.Precision.U8_LINEAR,
            Gimp.Precision.U16_NON_LINEAR
            #Gimp.Precision.U16_LINEAR
        }
        
        precision = temp_image.get_precision() 
        # print(precision)
        if precision not in allowed_precisions:
            # is_linear = precision .endswith("_LINEAR")
            # target_precision = Gimp.Precision.U16_LINEAR if is_linear else Gimp.Precision.U16_NON_LINEAR
            target_precision = Gimp.Precision.U16_NON_LINEAR
            
            pdb_proc_convert = Gimp.get_pdb().lookup_procedure('gimp-image-convert-precision')
            pdb_config_convert = pdb_proc_convert.create_config()
            pdb_config_convert.set_property('image', temp_image)
            pdb_config_convert.set_property('precision', target_precision)
            result_convert = pdb_proc_convert.run(pdb_config_convert)

        try:
            config = configparser.ConfigParser()
            config.read(os.path.expanduser('~/.turboprint/turboprint-user.cfg'))
            hotfolder_path = config.get('PrintFab_Settings', 'HotfolderDir').strip('"')
            
        except(configparser.Error, FileNotFoundError, KeyError) as e:
            try:
                config.read(os.path.expanduser('~/TurboPrint/turboprint-user.cfg'))
                hotfolder_path = config.get('PrintFab_Settings', 'HotfolderDir').strip('"')
                
            except(configparser.Error, FileNotFoundError, KeyError) as e:
                hotfolder_path = os.path.expanduser('~/TurboPrint/Hotfolder')
            
        os.makedirs(hotfolder_path, exist_ok=True)
        
        datetime_now = datetime.datetime.now()
        filename = datetime_now.strftime('%Y%m%d%H%M%S')
        filepath = os.path.join(hotfolder_path, f'{filename}.png')
        temppath = os.path.join(hotfolder_path, f'{filename}.png.tmp')
        
        #example_call: "file-tiff-export(run-mode, image, file, options, bigtiff, compression, save-transparent-pixels, cmyk, include-exif, include-iptc, include-xmp, include-color-profile, include-thumbnail, include-comment)"
        pdb_proc = Gimp.get_pdb().lookup_procedure('file-png-export')
        pdb_config = pdb_proc.create_config()
        
        pdb_config.set_property('run-mode', Gimp.RunMode.NONINTERACTIVE)
        pdb_config.set_property('image', temp_image)
        pdb_config.set_property('file', Gio.File.new_for_path(temppath))
        # pdb_config.set_property('save-transparent-pixels', True) #not supported by PNG
        pdb_config.set_property('compression', 1) #faster PNG saving
        pdb_config.set_property('include-exif', True)
        pdb_config.set_property('include-color-profile', True)
        
        ret = pdb_proc.run(pdb_config)
        
        os.rename(temppath, filepath)
        
        return ret
    
        # Gimp.file_save(run_mode, image, file, None)
        # return procedure.new_return_vwalues(Gimp.PDBStatusType.SUCCESS, None) 

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