# Module:         poImgFti
# Copyright:      Paul Obermeier 2026 / paul@poSoft.de
# First Version:  2026 / 03 / 14
#
# Distributed under BSD license.
#
# Module for handling FTI files with poFti and interpreting as images.

namespace eval poImgFti {
    variable ns [namespace current]

    namespace ensemble create

    namespace export PhotoFromFtiString
    namespace export PhotoFromFtiFile

    variable sCanvasId

    proc PhotoFromFtiString { iconString args } {
        variable sCanvasId

        set win .fti
        set sCanvasId $win.fr.c

        set opts [dict create \
            -verbose  false \
            -filename "" \
            -width    500 \
            -height   500 \
        ]

        if { [llength $args] > 1 } {
            foreach { key value } $args {
                if { [dict exists $opts $key] } {
                    if { $value eq "" } {
                        error "PhotoFromFti: No value specified for key \"$key\""
                    }
                    dict set opts $key $value
                } else {
                    error "PhotoFromFti: Unknown option \"$key\" specified"
                }
            }
        }

        set w [dict get $opts -width]
        set h [dict get $opts -height]
        if { $w <= 0 || $h <= 0 } {
            error "PhotoFromFti: Width or height are negative or zero."
        }

        set iconObj [poFti Icon new]
        set retVal [catch {$iconObj ReadFromString $iconString} errVal]
        if { $retVal != 0 } {
            error "PhotoFromFti: Cannot read icon [dict get $opts -filename] ($errVal)"
        }

        if { ! [winfo exists $sCanvasId] } {
            toplevel $win
            ttk::frame $win.fr
            pack $win.fr -expand 1 -fill both
            canvas $sCanvasId -width $w -height $h -background "#C9C9C9"
            pack $sCanvasId
            if { $::tcl_platform(os) eq "IRIX" } {
                raise $win
            } else {
                lower $win
            }
        } else {
            $sCanvasId configure -width $w -height $h
            $sCanvasId delete all
        }

        $iconObj Draw $sCanvasId -width $w -height $h
        set retVal [catch {$iconObj AsPhoto $sCanvasId} phImg]
        if { $retVal != 0 } {
            error "PhotoFromFti: Cannot create photo image ($phImg)"
        }

        $iconObj destroy

        return $phImg
    }

    proc PhotoFromFtiFile { fileName args } {
        set retVal [catch {open $fileName "r"} fp]
        if { $retVal != 0 } {
            error "PhotoFromFti: Could not open file \"$fileName\" for reading."
        }
        set iconData [read $fp]
        close $fp

        return [PhotoFromFtiString $iconData $args]
    }
}
