#!/usr/bin/env bash
if [[ "${LOADED_ODBMAPPER_LEVELS_SH+1}" == "" ]]; then
    export ODBMAPPER_LEVELS=${ODBMAPPER_LEVELS=}
    [[ -n $ODBMAPPER_LEVELS ]] || {
        ODBMAPPER_LEVELS="$DIR_ORTHOLOGER/etc/$URL_ORTHODB_API_VERSION/orthomapper_levels.sh"
    }
    [[ -f $ODBMAPPER_LEVELS ]] || {
        {
            echo
            echo "error: missing OrthoDB node definition file at"
            echo "ODBMAPPER_LEVELS = $ODBMAPPER_LEVELS"
            echo
        } 1>&2
    }

    # load lnodes
    source $ODBMAPPER_LEVELS

    #-----------------------------------------------
    # process and make some readonly
    readonly MAP_ROOT_CLADES
    declare -A MAP_NODE2CLADE

    MAP_ALL_NODES=()

    # fill and check some vars
    fill_required_arrays() {
        if ! isset "MAP_ROOT_CLADES"; then
            error_msg "required variable MAP_ROOT_CLADES is NOT set!"
            return 255
        fi
        local clade=""
        for clade in ${MAP_ROOT_CLADES[@]}; do
            local clup=${clade^^}
            local nodesvar="MAP_NODES_${clup}"
            local nodesarr="${nodesvar}[@]"
            if isset $nodesvar; then
                local node=""
                for node in ${!nodesarr}; do
                    MAP_NODE2CLADE[$node]=$clade
                done
                MAP_ALL_NODES+=($(echo "${!nodesarr}"))
            else
                error_msg "required variable $nodesvar is NOT set!"
                return 255
            fi
            local rootvar="MAP_NODE_ROOT_${clup}"
            if ! isset $rootvar; then
                error_msg "required variable $rootvar is NOT set!"
                return 255
            fi
            local root=${!rootvar}
            local found=0
            local x=""
            for x in ${!nodesarr}; do
                [[ "$x" == "$root" ]] && { found=1; break; }
            done
            if (( found == 0 )); then
                error_msg "MAP_NODES_${clup} does not contain the root clade as defined by MAP_NODE_ROOT_${clup}!"
                return 255
            fi
        done
        return 0
    }
    fill_required_arrays || {
        LOADED_ODBMAPPER_LEVELS_SH=255
        exit 255
    }

    [[ ${#MAP_NODE2CLADE[@]} -gt 0 ]] || fatal_msg "failed filling MAP_NODE2CLADE"
    [[ ${#MAP_ALL_NODES[@]}  -gt 0 ]] || fatal_msg "failed filling MAP_ALL_NODES"

    readonly MAP_NODE2CLADE
    readonly MAP_ALL_NODES

    
    LOADED_ODBMAPPER_LEVELS_SH=0
fi
