<?php
namespace boru\boruai\Vtiger;

use boru\boruai\BoruAI;
use boru\query\Query;
use Exception;

class VtigerModule {
    private static $modulesCache = [];
    /**
     * List active modules
     * @return array
     */
    public static function listModules() {
        if(empty(static::$modulesCache)) {
            static::loadModules();
        }
        return static::$modulesCache;
    }

    /**
     * Get module by name
     * @param string $name
     * @return array
     */
    public static function getModuleByName($name) {
        if(empty(static::$modulesCache)) {
            static::loadModules();
        }
        return static::getModule($name,"name");
    }

    /**
     * Get module by id
     * @param int $id
     * @return array
     */
    public static function getModuleById($id) {
        if(empty(static::$modulesCache)) {
            static::loadModules();
        }
        return static::getModule($id,"tabid");
    }

    /**
     * Get module by field value
     * @param mixed $value 
     * @param string $field 
     * @return mixed 
     * @throws Exception 
     */
    public static function getModule($value,$field="name") {
        if(empty(static::$modulesCache)) {
            static::loadModules();
        }
        foreach(static::$modulesCache as $module) {
            if($module[$field] == $value) {
                return $module;
            }
        }
        if($field == "name" && isset(static::$labelToModule[$value])) {
            return static::$labelToModule[$value];

        }
        return null;
    }

    private static $labelToModule = [];
    /**
     * Load modules
     * @return void
     */
    private static function loadModules($entityOnly=true) {
        static::$modulesCache = [];
        foreach(Query::create()->select("*")->from("vtiger_tab")->where("presence","=","0")->toRows() as $row) {
            if($entityOnly && $row->get("isentitytype") <= 0) {
                continue;
            }
            $rowArray = $row->asArray();
            if(isset($rowArray["tablabel"]) && !empty($rowArray["tablabel"])) {
                $rowArray["tablabel"] = Vtiger::translate($rowArray["name"],$rowArray["tablabel"]);
            }
            static::$modulesCache[$row->get("tabid")] = $rowArray;
            if($rowArray["tablabel"] != $rowArray["name"]) {
                static::$labelToModule[$rowArray["tablabel"]] = &static::$modulesCache[$row->get("tabid")];
            }
        }
        return static::$modulesCache;
    }
}