<?php
namespace boru\boruai\UI;

use boru\dot\Dot;

class Connector {
    private $requestVar;
    private $callback;

    private $instructions;

    private $data = [];
    private $value = null;

    public function __construct($requestVar,$callback=null) {
        $this->requestVar = $requestVar;
        $this->callback = $callback;
    }

    public function getRequestVar() {
        return $this->requestVar;
    }
    public function getCallback() {
        return $this->callback;
    }
    public function getInstructions() {
        if($this->data) {
            return $this->instructions;
        }
    }
    public function getData() {
        return $this->data;
    }

    public function setRequestVar($var) {
        if($var !== null) {
            $this->requestVar = $var;
        }
        return $this->requestVar;
    }
    public function setCallback($callback) {
        if($callback !== null) {
            $this->callback = $callback;
        }
        return $this->callback;
    }

    public function setInstructions($instructions) {
        if($instructions !== null) {
            $this->instructions = $instructions;
        }
        return $this->instructions;
    }

    public function get($key=null,$default=null) {
        if($key === null || !is_array($this->data)) {
            return $this->data;
        }
        return Dot::get($this->data,$key,$default);
    }

    public function getValue() {
        return $this->value;
    }
    public function isTriggered() {
        return $this->value !== null;
    }
    private function captureValue($webUI) {
        if($this->requestVar === true) {
            $this->value = true;
            return;
        }
        $value = $webUI->request($this->requestVar,false);
        if($value === false) {
            $value = $webUI->body($this->requestVar,false);
        }
        if($value === false) {
            return false;
        }
        $this->value = $value;
    }

    /**
     * Handle the request
     *
     * @param WebUI $webUI
     * @return void
     */
    public function handleRequest($webUI) {
        $this->captureValue($webUI);
        if($this->value === false) {
            return;
        }
        if($this->getCallback()) {
            $callback = $this->getCallback();
            if(is_callable($callback)) {
                $this->data = call_user_func($callback,$this->value,$webUI);
            } else {
                $this->data = $callback;
            }
        } else {
            $this->data = $this->value;
        }
    }

    public static function create($requestVar,$callback=null) {
        return new static($requestVar,$callback);
    }
}