<?php
namespace boru\boruai\UI;

use boru\boruai\BoruAI;

class Tools {
    private $enabled = [];
    private $forced = [];
    private $available = [];


    public function getEnabled() {
        return array_values($this->enabled);
    }
    public function getForced() {
        return array_values($this->forced);
    }
    public function getForChat() {
        $array = [];
        foreach($this->enabled as $k=>$v) {
            $array[$k] = $v;
        }
        foreach($this->forced as $k=>$v) {
            if(!isset($array[$k])) {
                $array[$k] = $v;
            }
        }
        return array_values($array);
    }

    public function add($tool,$enabled=false,$forced=false) {
        if(is_array($tool)) {
            foreach($tool as $t) {
                $this->add($t,$enabled,$forced);
            }
            return;
        }
        if(!is_object($tool)) {
            $tool = BoruAI::loadTool($tool);
        }
        if($tool && method_exists($tool,"forResponse")) {
            $this->available[$tool->name()] = $tool;
            if($forced) {
                $this->forced[$tool->name()] = $tool;
            }
            if($enabled) {
                $this->enabled[$tool->name()] = $tool;
            }
        }
    }
    public function get($name=null) {
        if($name !== null) {
            if(is_object($name)) {
                if(method_exists($name,"name")) {
                    $name = $name->name();
                } else {
                    $name = get_class($name);
                }
            }
            if(isset($this->available[$name])) {
                return $this->available[$name];
            }
            return false;
        }
        $tools = [];
        foreach($this->forced as $tool) {
            $tools[$tool->name()] = $tool;
        }
        foreach($this->enabled as $tool) {
            if(!isset($tools[$tool->name()])) {
                $tools[$tool->name()] = $tool;
            }
        }
        return array_values($tools);
    }
    public function enableTool($toolName) {
        if(is_array($toolName)) {
            foreach($toolName as $t) {
                $this->enableTool($t);
            }
            return true;
        }
        if(($tool = $this->get($toolName)) !== false) {
            $toolName = $tool->name();
            $this->enabled[$toolName] = $tool;
            return true;
        }
        return false;
    }
    public function disableTool($toolName) {
        if(is_array($toolName)) {
            foreach($toolName as $t) {
                $this->disableTool($t);
            }
            return true;
        }
        if(($tool = $this->get($toolName)) !== false) {
            $toolName = $tool->name();
            if(isset($this->enabled[$toolName])) {
                unset($this->enabled[$toolName]);
                return true;
            }
        }
        return false;
    }
}