<?php

namespace Application\Controller;

use Application\Form\item\LogicModel;
use Application\Form\LogicFormModel;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\components\AnalysisHelper;
use Application\Service\Extension\Helper\FileHelper;
use Application\Service\Extension\Laminas;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;

class DashboardController extends AbstractActionController // BaseController
{
    public function __construct()
    {
//        if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === '/dashboard') {
//            return;
//        }
//
//        Laminas::$serviceManager->identity->getId();
    }

    public function indexAction()
   {
       $view = new ViewModel();
       $view->setTemplate('dashboard/index');
       $view->setVariables([
           'filesCount' => count(FileHelper::getFiles(APP_PATH . '/runtime/' . date('Y-m-d')))
       ]);

       return $view;
   }

   public function fileTimestampAction(): ViewModel
   {
       $view = new ViewModel();
       $view->setTemplate('dashboard/fileTimestamp');
       $view->setVariables([
           'files' => FileHelper::getFiles(APP_PATH . '/config')
       ]);

       return $view;
   }

    public function apiFileTimestampAction()
    {
        $path = $this->params()->fromPost('path');
        $files = FileHelper::getFiles(APP_PATH . '/' . trim($path, '/'));

        $r = [];
        foreach ($files as $file) {
            $r[] = [
                'path' => $file,
                'timestamp' => date("Y-m-d H:i:s", filemtime($file))
            ];
        }
        return $this->RenderApiJson()->Success($r);
    }

    public function exceptionAction(): ViewModel
    {
        $view = new ViewModel();
        $view->setTemplate('dashboard/exception');
        $view->setVariables([
            'files' => FileHelper::getFiles(APP_PATH . '/runtime/' . date('Y-m-d'))
        ]);

        return $view;
    }

    public function apiExceptionAction(): ViewModel
    {
        $path = $this->params()->fromPost('date');
        $files = FileHelper::getFiles(APP_PATH . '/runtime/' . trim($path, '/'));
        return $this->RenderApiJson()->Success($files);
    }


    public function apiExceptionDetailAction(): ViewModel
    {
        $file = $this->params()->fromPost('path');

        return $this->RenderApiJson()->Success([file_get_contents($file)]);
    }

    public function unitTestAction(): ViewModel
    {
        $view = new ViewModel();
        $view->setTemplate('dashboard/unitTest');
//        $view->setVariables([
//            'files' => FileHelper::getFiles(APP_PATH . '/runtime/' . date('Y-m-d'))
//        ]);

        return $view;
    }

    public function apiUnitTestAction(): ViewModel
    {
        system('php' . ' -d memory_limit=-1 ' . APP_PATH . '/vendor/bin/phpunit');die;
        $view = new ViewModel();
        $view->setTemplate('dashboard/unitTest');
//        $view->setVariables([
//            'files' => FileHelper::getFiles(APP_PATH . '/runtime/' . date('Y-m-d'))
//        ]);

        return $view;
    }

    public function redisAction(): ViewModel
    {
        $view = new ViewModel();
        $view->setTemplate('dashboard/redis');
//        $view->setVariables([
//            'files' => FileHelper::getFiles(APP_PATH . '/runtime/' . date('Y-m-d'))
//        ]);

        return $view;
    }

    public function apiRedisAction()
    {
        $method = $this->params()->fromPost('params');
        $params = explode(' ', $method);
        $redisMethod = array_shift($params);

        $val = Laminas::$serviceManager->redisExtend->getRedisInstance()->{$redisMethod}(...$params);

        return $this->RenderApiJson()->Success(!is_array($val) ? array($val) : $val);
    }

    public function formLogAction()
    {
        $view = new ViewModel();
        $view->setTemplate('dashboard/formLog');
        return $view;
    }

    public function apiFormLogAction()
    {
        $contentId = $this->params()->fromPost('params');
        $query = Laminas::$serviceManager->patientFormContentUpdatedLog->fetchAll([
            'where' => [
                'content_id' => $contentId
            ]
        ]) ?: [];

        return $this->RenderApiJson()->Success($query);
    }

    public function analysisAction()
    {
        $view = new ViewModel();
        $view->setTemplate('dashboard/analysis');
        $val = $this->getAnalysisData();
        $view->setVariables([
            'data' => $val,
            'title' => ArrayHelper::getColumn($val, 'name')
        ]);
        return $view;
    }

    public function analysisResponseTimeAction()
    {
        $view = new ViewModel();
        $view->setTemplate('dashboard/analysisResponseTime');
        $val = $this->getAnalysisData();
        $view->setVariables([
            'data' => $val,
            'title' => ArrayHelper::getColumn($val, 'name'),
        ]);
        return $view;
    }

    private function getAnalysisData()
    {
        $res = $data = [];
        for ($i = 0; $i < 24; $i++) {
            $value = Laminas::$serviceManager->redisExtend->getRedisInstance()->hGetAll(AnalysisHelper::getRequestTimesKey($i));
            foreach ($value as $url => $item) {
                if (!isset($data[$url])) {
                    $data[$url] = array_fill(0, 24, 0);
                }
                $data[$url][$i] = $item;
            }
        }

        foreach ($data as $url => $item) {
            $slow = Laminas::$serviceManager->redisExtend->getRedisInstance()->lLen(AnalysisHelper::getResponseTimeKey() . ':' . $url);
            $total = array_sum($item);
            $res[] = [
                'name' => $url,
                'data' => $item,
                'total' => $total,
                'slow' => $slow,
                'normal' => $total - $slow
            ];
        }

        return $res;
    }

    public function apiAnalysisResponseTimeAction()
    {
        $url = $this->params()->fromQuery('url');
        $val = Laminas::$serviceManager->redisExtend->getRedisInstance()->lRange(AnalysisHelper::getResponseTimeKey() . ':' . $url, 0, -1);

        return $this->RenderApiJson()->Success($val);
    }
}