#!/bin/bash
#
# Copyright (C) 2023 MOXA Inc. All rights reserved.
# This software is distributed under the terms of the MOXA SOFTWARE NOTICE.
# See the file LICENSE for details.
#
# Authors:
#       2023  Wilson YS Huang  <wilsonys.huang@moxa.com>

source "scripts/lib/colors.sh"

LOG_FILE="/dev/null"
LOG_LEVEL="info"

_log_level() {
        local lv

        case "$1" in
        debug) lv=0 ;;
        info) lv=1 ;;
        warn) lv=2 ;;
        error) lv=3 ;;
        esac

        echo $lv
}

_log() {
        local lv="$1"
        local message="$2"
        local timestamp
        local min_lv

        timestamp="$(date +%F-%r)"
        min_lv=$(_log_level "$LOG_LEVEL")

        if ((lv >= min_lv)); then
                echo "${message}"
                echo "${timestamp} ${message}" >>"${LOG_FILE}"
        fi
}

log::init() {
        local file="$1"
        local min_level="$2"

        if [[ -n "$file" ]]; then
                LOG_FILE="$file"
        fi

        if [[ -n "$min_level" ]]; then
                LOG_LEVEL=$min_level
        fi
}

log::debug() {
        local msg="$1"
        local lv
        lv=$(_log_level debug)

        _log "$lv" "[$(colors::green debug)] ${msg}"
}

log::info() {
        local msg="$1"
        local lv
        lv=$(_log_level info)

        _log "$lv" "[info] ${msg}"
}

log::warn() {
        local msg="$1"
        local lv
        lv=$(_log_level warn)

        _log "$lv" "[$(colors::yellow warn)] ${msg}"
}

log::error() {
        local msg="$1"
        local lv
        lv=$(_log_level error)

        _log "$lv" "[$(colors::red error)] ${msg}"
}
