<?php


namespace App\Http\Controllers;
use App\Mqtt_data_request;
use App\MqttTopic;
use App\Request_users;
use App\Stanice;
use Exception;
use Salman\Mqtt\MqttClass\Mqtt;


class MqttSubscribeController extends Mqtt
{
    public CONST SUBSCRIBEUSER = 1;
    protected $Insertuser;

    public function setHost($host): void
    {
        $this->host = $host;
    }


    public function subscribeToTopic($topic=''): void
    {
        /**
         * nastaveni uživatele z DB pro tohoto klienta
         */
        $this->setInsertUserName();

        try
        {
            $this->ConnectAndSubscribe($topic, static function($topic, $msg)
                {
                    /** @var array $topic */
                    $topic = explode('/', (string)$topic);
                    $pocet = count($topic);
                    $posledni = $pocet-1;
                    $n = new AutomatickeBanovaniController();
                    if(is_numeric($topic[$posledni]) && Stanice::isBanned($topic[$posledni])[0]->ban === 0 && self::kontrolaTematu($topic) && $n->banChecker($topic[$posledni]))
                    {
                        Stanice::staniceExist($topic[$posledni], self::SUBSCRIBEUSER);
                        $db = new Mqtt_data_request(['id_stanice'=>$topic[$posledni],'topic'=>'data', 'data'=>$msg, 'vlozil' => self::SUBSCRIBEUSER]);
                        $db->save();
                        dump('prijate data');
                    }
                    else
                    {
                        dump('nebylo ID za posledním / nebo zabanovano');
                    }
                }, $this->Insertuser);
        }
        catch (Exception $e)
        {
            dump($e);
        }

    }

    /**
     * @param array $topic
     * @return bool
     */
    public static function kontrolaTematu(array $topic): bool
    {
        $aktivniTopic = MqttTopic::whereAktivni(1)->first();
        if($aktivniTopic === null)
        {
            $aktivniTopic = '#';
        }
        $aktivniTopicPostupne = explode('/',$aktivniTopic->topic);
        $pocetDBtopic = count($aktivniTopicPostupne);
        $pocetOK=0;
        foreach ($topic as $id => $tema)
        {
            if ($aktivniTopicPostupne[$id]==='#')
            {
                return true;
            }

            if($aktivniTopicPostupne[$id] === '+')
            {
                $pocetOK++;
            }
            elseif($aktivniTopicPostupne[$id] === $tema)
            {
                $pocetOK++;
            }
            else
            {
                return  false;
            }
        }

        return $pocetOK === $pocetDBtopic;
    }

    public function setInsertUserName(): void
    {
        $this->Insertuser = Request_users::findOrFail(self::SUBSCRIBEUSER)->name;
    }

}
