#
# Copyright (c) 2022-2024 Andrea Biscuola <a@abiscuola.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

namespace eval log {
	namespace export open write close console enable

	namespace ensemble create

	set enabled 1
}

proc ::log::open {network chan} {
	set dir "$::logdir/$network"

	if {[catch {file mkdir $dir} errstr]} {
		console "::log::open: $errstr

		return -code error "$errstr"
	}

	if {![catch {set f [::open "$dir/$chan" a+ 0640]} errstr]} {
		fconfigure $f -blocking 0

		return $f
	} else {
		console "::log::open: $errstr"

		return -code error "$errstr"
	}
}

proc ::log::write {chan nick msg timestamp} {
	variable enabled

	if {$chan == -1 || $enabled == 0} {return}

	set date [clock format $timestamp -format "%Y-%m-%dT%H:%M:%S"]

	if {[catch {puts $chan [format "%s <%s>: %s" $date $nick $msg]} errstr]} {
		console "::log::write: $errstr"
	} else {
		flush $chan
	}
}

proc ::log::close {chan} {
	if {$chan == -1} {return}

	fconfigure $chan -blocking 1

	if {[catch {::close $chan} errstr]} {
		console "::log::close: $errstr"

		return -code error "$errstr"
	}
}

proc ::log::console {text} {
	set date [clock format [clock seconds] -format "%Y-%m-%dT%H:%M:%S"]

	puts stderr [format "%s %s" $date $text]

	flush stderr
}

proc ::log::enable {status} {
	variable enabled

	set enabled $status
}
