<?php

namespace app\controllers;

use PEAR2\Net\RouterOS;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\mikrotik\MikrotikSideMenu;
use app\models\mikrotik\MikrotikForm;
use yii\web\Session;
use yii\helpers\Url;
use app\models\mikrotik\ip\neighbors\Neighbors;
use app\models\mikrotik\MikrotikConnect;
use app\models\mikrotik\MikrotikCrypt;
use app\models\UserForm;
use app\models\User;
use app\models\mikrotik\Graphs;
use yii\data\ArrayDataProvider;

class MikrotikController extends Controller {

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'graphs', 'disconnect'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => [],
                        'allow' => true,
                        'roles' => ['admin'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex() {
        $menu = new MikrotikSideMenu();
        $model = new MikrotikForm();
        $mcrypt = new MikrotikCrypt();
        $session = Yii::$app->session;

        $user = User::findByUsername(Yii::$app->user->getIdentity()->username);
        if ($session->get('connect_to') != null) {
            $model->ip = $session->get('connect_to');
        }
        $ip = $user->mikrotik;
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($session->get('connect_to') != null) {
                $session->remove('connect_to');
            }
            //return var_dump($model->ip);
            $login = (explode(" as ", $model->ip));
            if (isset($login[1])) {
                $model->ip = $login[0];
                $model->login = $login[1];
            }
            $session->open();
            $session->set('active', 'no');
            $session->set('ip', chop(trim($model->ip)));
            $session->set('login', $model->login);
            if ($model->pwd != '') {
                $session->set('pwd', $mcrypt->Crypt($model->pwd, pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3")));
            } else {
                $session->set('pwd', $model->pwd);
            }
            $session->set('last_activity', time());
            $con = new MikrotikConnect();
            $con->getConnection();
            if ($session->get('active') == 'yes') {
                return $this->redirect(Url::toRoute('mikrotik/graphs'));
            }
        }
        if ($session->get('ip') != null) {
            $neighbor = new Neighbors();
            $provider = $neighbor->getAll();
            $provide = new ArrayDataProvider([
                'allModels' => $provider,
                'key' => 'address',
                'sort' => [
                    'attributes' => [
                        'address',
                        'address4',
                        'mac_address',
                        'identity',
                        'platform',
                        'version',
                        'board',
                    ],
                ],
                'pagination' => [
                    'pageSize' => 20,
                ],
            ]);
        } else {
            $provide = null;
        }
        return $this->render('index', [
                    'model' => $model,
                    'menu' => $menu->getMenu(),
                    'ip' => $ip,
                    'provider' => $provide,
        ]);
    }

    public function actionDisconnect() {
        $session = Yii::$app->session;
        $session->remove('ip');
        $session->remove('login');
        $session->remove('pwd');
        return $this->redirect(Url::toRoute('mikrotik/index'));
    }

    public function actionConnect() {
        $session = Yii::$app->session;
        $session->remove('ip');
        $session->remove('login');
        $session->remove('pwd');
        $session->set('connect_to', Yii::$app->request->get('id'));

        return $this->redirect(Url::toRoute('mikrotik/index'));
    }

    public function actionGraphs() {
        $session = Yii::$app->session;
        $menu = new MikrotikSideMenu();
        $model = new Graphs();
        $que = $model->getAllQueues();
        $int = $model->getAllInterfaces();

        $often = 'daily';
        $type = Yii::$app->request->get('type');
        if ($type != null) {
            $often = $type;
        }
        $x = '0';
        foreach ($que as $value) {
            $valu = str_replace(" ", "_", $value);
            if (@getimagesize('http://' . $session->get('ip') . '/graphs/queue/' . $valu . '/' . $often . '.gif')[0] > '300') {
                @copy('http://' . $session->get('ip') . '/graphs/queue/' . $valu . '/' . $often . '.gif', 'graphs/' . $valu . '_' . $often . '.gif');
            } else {

                unset($que[$x]);
            }
            $x++;
        }
        $i = '0';
        foreach ($int as $value) {

            $valu = str_replace(" ", "_", $value);
            if (@getimagesize('http://' . $session->get('ip') . '/graphs/iface/' . $valu . '/' . $often . '.gif')[0] > '300') {

                @copy('http://' . $session->get('ip') . '/graphs/iface/' . $valu . '/' . $often . '.gif', 'graphs/' . $valu . '_' . $often . '.gif');
            } else {

                unset($int[$i]);
            }
            $i++;
        }

        @copy('http://' . $session->get('ip') . '/graphs/cpu/' . $often . '.gif', 'graphs/cpu_' . $often . '.gif');



        @copy('http://' . $session->get('ip') . '/graphs/ram/' . $often . '.gif', 'graphs/ram_' . $often . '.gif');


        @copy('http://' . $session->get('ip') . '/graphs/hdd/' . $often . '.gif', 'graphs/hdd_' . $often . '.gif');


        return $this->render('graphs', [
                    'menu' => $menu->getMenu(),
                    'que' => $que,
                    'int' => $int,
                    'often' => $often,
        ]);
    }

}
