<?php

namespace app\models\mikrotik;

require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar';

use PEAR2\Net\RouterOS;
use PEAR2\Net\Transmitter\NetworkStream;
use yii\base\ErrorException;
use yii\web\Session;
use Yii;
use yii\helpers\Url;
use app\models\mikrotik\MikrotikCrypt;

/**
 * Description of MikrotikConnect
 *
 * @author Lukas
 */
class MikrotikConnect {

   
    private $ip; 
    private $login;
    private $pwd;
    private $connection;

    /**
     * Call this method to get singleton
     *
     * @return MikrotikConnect
     */
    public static function Instance() {
        static $inst = null;
        $session = Yii::$app->session;
        if ((time() - $session->get('last_activity') > 1800) OR ( $session->get('active') == 'no')) {
            $session->remove('ip');
            $session->remove('login');
            $session->remove('pwd');
            Yii::$app->session->setFlash('message', 'You Have Been Disconnected');
            return Yii::$app->getResponse()->redirect(Url::toRoute('mikrotik/index'));
        }
        $session->set('last_activity', time());
        if ($inst === null) {

            $inst = new MikrotikConnect();
        }
        return $inst;
    }

    function __construct() {
        $mcrypt = new MikrotikCrypt();
        $session = Yii::$app->session;
        $this->ip = $session->get('ip');
        $this->pwd = $session->get('pwd');
        if ($this->pwd != '') {
            $this->pwd = trim($mcrypt->Decrypt($session->get('pwd'), pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3")));
        }
        $this->login = $session->get('login');
        $context = stream_context_create(
                array(
                    'ssl' => array(
                        'verify_peer' => true,
                        'cafile' => 'conf/ssl.crt/server.crt'
                    )
                )
        );
        try {
            //$this->connection = new RouterOS\Client($this->ip, $this->login, $this->pwd, 8729, false, null, NetworkStream::CRYPTO_TLS); 
            //$this->connection = new RouterOS\Client($this->ip, $this->login, $this->pwd, 8729, false, null, NetworkStream::CRYPTO_TLS, $context);

            $this->connection = new RouterOS\Client($this->ip, $this->login, $this->pwd);
            
        } catch (DataFlowException $e) {
            Yii::$app->session->setFlash('message', $e);
            return Yii::$app->getResponse()->redirect(Url::toRoute('mikrotik/index'));
        } finally {
            if ($this->connection == null) {
                $session->remove('ip');
                $session->remove('login');
                $session->remove('pwd');

                return Yii::$app->getResponse()->redirect(Url::toRoute('mikrotik/index'));
            }
        }
        $session->set('active', 'yes');
    }

    public function getConnection() {

        return $this->connection;
    }

    function __destruct() {
        $this->connection->close();
    }

}
