<?php

class StatsController extends Controller {

    public function getRecentTransitsDay() {
        return $this->getRecentTransits(DateHelper::ensureObjectEx()->getToday());
    }

    public function getRecentTransitsWeek() {
        return $this->getRecentTransits(DateHelper::ensureObjectEx()->getFirstDayOfWeek());
    }

    public function getRecentTransitsMonth() {
        return $this->getRecentTransits(DateHelper::ensureObjectEx()->getFirstDayOfMonth());
    }

    public function getRecentTransits($date) {
        $time_start = microtime(true);
        $result = query('SELECT SUM(Counter) AS cnt FROM statstable IGNORE INDEX(Index_gate) WHERE StartDateTime >= :tm', array(':tm' => $date));
        Yii::log("\t Time execution \t".(microtime(true) - $time_start)." s", "info", "stats.getRecentTransits.20");
        if (is_numeric($result->cnt)) {
            return $result->cnt;
        } else {
            return 0;
        }
    }

    protected function beforeAction($event) {
        return parent::beforeAction($event);
    }

    public function actionStatusBox() {
        return $this->renderPartial('statusBox');
    }

    public function actionIndex() {
        access_denied_check("statistics");
        $gates = Gate::getAllGates();
        $this->render('index', array('gates' => $gates));
    }

    public function actionDangerousGoods() {
        access_denied_check("statistics");
        $gates = Gate::getAllGates();
        $this->render('dangerousGoods/index', array('gates' => $gates));
    }

    public function actionFilter(array $gates, array $vehiclesClass, $startTimestamp, $endTimestamp, $minSpeed, $maxSpeed, $granularity, $startTime, $endTime) {
        access_denied_check("statistics");
        $statsQuery = new StatsQuery();
        $dataProvider = $statsQuery->getStatsData(
                array(
                    'vehiclesClass' => $vehiclesClass,
                    'gates' => $gates,
                    'startTimestamp' => $startTimestamp,
                    'endTimestamp' => $endTimestamp,
                    'minSpeed' => $minSpeed,
                    'maxSpeed' => $maxSpeed,
                    'granularity' => $granularity,
                    'startTime' => $startTime,
                    'endTime' => $endTime,
                )
        );

        $graphData = VehicleStatGraphEncoder::encode($dataProvider->getData(), 'StartDateTime', 'Counter', $granularity);
        $this->renderPartial('_results', array('dataProvider' => $dataProvider, 'graphData' => $graphData));
    }

    public function actionEventsManagement() {
        access_denied_check("statistics");

        access_denied_check("statistics_events_management");

        set_time_limit(3000);

        $violationsCountByTimespanStatsData = NULL;
        $approvedViolationsCountByTimespanStatsData = NULL;
        $invalidViolationsCountByTimespanStatsData = NULL;
        $pendingViolationsCountByTimespanStatsData = NULL;
        $exportedEventsCountByTimespanStatsData = NULL;
        $violationsCountByGate = NULL;
        $approvedViolationsCountByGate = NULL;
        $invalidViolationsCountByGate = NULL;
        $exportedEventsCountByGate = NULL;

        $gateModel = Gate::model();
        $gates = $gateModel->findAll();

        $eventsStatisticsSearchForm = new EventsStatisticsSearchForm();
        if (isset($_POST['EventsStatisticsSearchForm'])) {

            $eventsStatisticsSearchForm->setAttributes($_POST['EventsStatisticsSearchForm'], false);

            $searchFilters = array();

            $validationResult = $eventsStatisticsSearchForm->validate();
            if (!$validationResult) {

                $this->render("eventsManagement/index", array(
                    'gates' => $gates,
                    'eventsStatisticsSearchForm' => $eventsStatisticsSearchForm,
                    'validationErrors' => $eventsStatisticsSearchForm->getErrors()
                        )
                );

                return;
            }

            $startDateTime = DateTime::createFromFormat(
                            getFormat_DateTime(), $eventsStatisticsSearchForm->startDateTime
            );

            $endDateTime = DateTime::createFromFormat(
                            getFormat_DateTime(), $eventsStatisticsSearchForm->endDateTime
            );

            if (!empty($eventsStatisticsSearchForm->gates)) {

                $searchFilters = array_merge($searchFilters, array('gates' => $eventsStatisticsSearchForm->gates)
                );
            }

            if (!empty($eventsStatisticsSearchForm->startTimeSlot) && !empty($eventsStatisticsSearchForm->endTimeSlot)) {

                $startTimeSlot = DateTime::createFromFormat(
                                getFormat_Time(), $eventsStatisticsSearchForm->startTimeSlot
                );

                $endTimeSlot = DateTime::createFromFormat(
                                getFormat_Time(), $eventsStatisticsSearchForm->endTimeSlot
                );

                $searchFilters = array_merge($searchFilters, array('timeSlot' => array(
                        'startTimeSlot' => $startTimeSlot,
                        'endTimeSlot' => $endTimeSlot
                    )
                        )
                );
            }

//            $eventsStatistics = EventsStatistics::model();

            $violationsCountByTimespanStatsData = array();

            $approvedViolationsCountByTimespanStatsData = array();

            $invalidViolationsCountByTimespanStatsData = array();

            $pendingViolationsCountByTimespanStatsData = array();

            $exportedEventsCountByTimespanStatsData = array();

            $violationsCountByGate = array();

            $approvedViolationsCountByGate = array();

            $invalidViolationsCountByGate = array();

            $exportedEventsCountByGate = array();


            $gateFilter = "";

            if (array_key_exists("gates", $searchFilters)) {
                $gateFilter = " AND Gate IN (" . join(',', array_values($searchFilters["gates"])) . ") ";
                $targetGates = Gate::model()->findAllByPk(array_values($searchFilters["gates"]));
            } else {
                $targetGates = Gate::model()->findAll();
            }

            $gateMapping = array();

            foreach ($targetGates as $currentTargetGate) {
                $violationsCountByGate[$currentTargetGate->Descrizione] = 0;
                $approvedViolationsCountByGate[$currentTargetGate->Descrizione] = 0;
                $invalidViolationsCountByGate[$currentTargetGate->Descrizione] = 0;
                $exportedEventsCountByGate[$currentTargetGate->Descrizione] = 0;
                $gateMapping[$currentTargetGate->Gate] = $currentTargetGate->Descrizione;
            }

            $startDateToUse = $startDateTime->format('Y-m-d');
            $endDateToUse = $endDateTime->format('Y-m-d');

            $startTimeSlotToUse = isset($startTimeSlot) ? $startTimeSlot->format('H:i:s') : null;
            $endTimeSlotToUse = isset($endTimeSlot) ? $endTimeSlot->format('H:i:s') : null;

            $timeSlotQueryPart = '';
            if (!is_null($startTimeSlotToUse) && !is_null($endTimeSlotToUse)) {
                $timeSlotQueryPart = " AND time(StartTime) between '$startTimeSlotToUse' AND '$endTimeSlotToUse'";
            }

            $queryWithoutExported = "SELECT 
                                        validation_result,
                                        COUNT(*) AS conteggio,
                                        StartTime,
                                        DATE(StartTime) AS data_multa,
                                        Gate
                                    FROM
                                        eventserverdb.storicotable " .
                    str_replace("AND", "WHERE", $gateFilter) .
                    " GROUP BY Gate , data_multa , validation_result
                                    HAVING StartTime BETWEEN '$startDateToUse' AND '$endDateToUse' $timeSlotQueryPart";

            $queryForTheExported = "SELECT
                                        COUNT(*) AS conteggio,
                                        StartTime,
                                        DATE(StartTime) AS data_multa,
                                        Gate
                                    FROM
                                        eventserverdb.storicotable
                                    WHERE
                                        Protocol <> '' and Protocol <> 'NO_MULTA' $gateFilter
                                    GROUP BY Gate , data_multa , validation_result
                                    HAVING StartTime BETWEEN '$startDateToUse' AND '$endDateToUse'";


//            echo $queryWithoutExported . '<br>';
//            print_r($gateMapping);
//            die();

            $targetViolations = EventsStatistics::model()->findAllBySql($queryWithoutExported);

//            echo "count: " . count($targetViolations) . '<br>';

            while ($startDateTime <= $endDateTime) {
                $approvedViolationsCountByTimespanStatsData[$startDateTime->format('Y-m-d')] = 0;
                $invalidViolationsCountByTimespanStatsData[$startDateTime->format('Y-m-d')] = 0;
                $violationsCountByTimespanStatsData[$startDateTime->format('Y-m-d')] = 0;
                $pendingViolationsCountByTimespanStatsData[$startDateTime->format('Y-m-d')] = 0;
                $exportedEventsCountByTimespanStatsData[$startDateTime->format('Y-m-d')] = 0;
                $startDateTime->modify("+1 day");
            }


            foreach ($targetViolations as $currentViolation) {
                $currentKey = $currentViolation->data_multa;
                $currentGateKey = $gateMapping[$currentViolation->Gate];
                $violationsCountByTimespanStatsData[$currentKey] += $currentViolation->conteggio;
                $violationsCountByGate[$currentGateKey] += $currentViolation->conteggio;
                switch ($currentViolation["validation_result"]) {
                    case "approved":
                        $approvedViolationsCountByTimespanStatsData[$currentKey] += $currentViolation->conteggio;
                        $approvedViolationsCountByGate[$currentGateKey] += $currentViolation->conteggio;
                        break;
                    case "pending":
                        $pendingViolationsCountByTimespanStatsData[$currentKey] += $currentViolation->conteggio;
                        break;
                    case "invalid":
                        $invalidViolationsCountByTimespanStatsData[$currentKey] += $currentViolation->conteggio;
                        $invalidViolationsCountByGate[$currentGateKey] += $currentViolation->conteggio;
                        break;
                }
            }



            $targetViolations = EventsStatistics::model()->findAllBySql($queryForTheExported);


            foreach ($targetViolations as $currentViolation) {
                $currentKey = $currentViolation->data_multa;
                $currentGateKey = $gateMapping[$currentViolation->Gate];
                $exportedEventsCountByTimespanStatsData[$currentKey] += $currentViolation->conteggio;
                $exportedEventsCountByGate[$currentGateKey] += $currentViolation->conteggio;
            }











//            $violationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByOccurenceDateTime(
//                    $startDateTime, $endDateTime, $searchFilters);
//
//            $approvedViolationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByOccurenceDateTime(
//                    $startDateTime, $endDateTime, array_merge($searchFilters, array(
//                'approvedViolations' => TRUE
//                            )
//                    )
//            );
//
//            $invalidViolationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByOccurenceDateTime(
//                    $startDateTime, $endDateTime, array_merge($searchFilters, array(
//                'invalidViolations' => TRUE
//                            )
//                    )
//            );
//
//            $pendingViolationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByOccurenceDateTime(
//                    $startDateTime, $endDateTime, array_merge($searchFilters, array(
//                'pendingViolations' => TRUE
//                            )
//                    )
//            );
//
//            $exportedEventsCountByTimespanStatsData = $eventsStatistics->getEventsCountByOccurenceDateTime(
//                    $startDateTime, $endDateTime, array_merge($searchFilters, array(
//                'exportedEvents' => TRUE
//                            )
//                    )
//            );
//
//            $violationsCountByGate = $eventsStatistics->getViolationsCountByGate(
//                    array_merge($searchFilters, array(
//                'eventStartDateTime' => $startDateTime,
//                'eventEndDateTime' => $endDateTime
//                            )
//                    )
//            );
//
//            $approvedViolationsCountByGate = $eventsStatistics->getViolationsCountByGate(
//                    array_merge($searchFilters, array(
//                'eventStartDateTime' => $startDateTime,
//                'eventEndDateTime' => $endDateTime,
//                'approvedViolations' => TRUE
//                            )
//                    )
//            );
//
//            $invalidViolationsCountByGate = $eventsStatistics->getViolationsCountByGate(
//                    array_merge($searchFilters, array(
//                'eventStartDateTime' => $startDateTime,
//                'eventEndDateTime' => $endDateTime,
//                'invalidViolations' => TRUE
//                            )
//                    )
//            );
//
//            $exportedEventsCountByGate = $eventsStatistics->getEventsCountByGate(
//                    array_merge($searchFilters, array(
//                'eventStartDateTime' => $startDateTime,
//                'eventEndDateTime' => $endDateTime,
//                'exportedEvents' => TRUE
//                            )
//                    )
//            );
        }

//        echo '<br><br>violationsCountByTimespanStatsData';
//        print_r($violationsCountByTimespanStatsData);
//        echo '<br><br>approvedViolationsCountByTimespanStatsData';
//        print_r($approvedViolationsCountByTimespanStatsData);
//        echo '<br><br>invalidViolationsCountByTimespanStatsData';
//        print_r($invalidViolationsCountByTimespanStatsData);
//        echo '<br><br>pendingViolationsCountByTimespanStatsData';
//        print_r($pendingViolationsCountByTimespanStatsData);
//        echo '<br><br>exportedEventsCountByTimespanStatsData';
//        print_r($exportedEventsCountByTimespanStatsData);
//        echo '<br><br>violationsCountByGate';
//        print_r($violationsCountByGate);
//        echo '<br><br>approvedViolationsCountByGate';
//        print_r($approvedViolationsCountByGate);
//        echo '<br><br>invalidViolationsCountByGate';
//        print_r($invalidViolationsCountByGate);
//        echo '<br><br>exportedEventsCountByGate';
//        print_r($exportedEventsCountByGate);
//
//        die();
        $this->render("eventsManagement/index", array(
            'gates' => $gates,
            'eventsStatisticsSearchForm' => $eventsStatisticsSearchForm,
            'violationsCountByTimespanStatsData' => $violationsCountByTimespanStatsData,
            'approvedViolationsCountByTimespanStatsData' => $approvedViolationsCountByTimespanStatsData,
            'invalidViolationsCountByTimespanStatsData' => $invalidViolationsCountByTimespanStatsData,
            'pendingViolationsCountByTimespanStatsData' => $pendingViolationsCountByTimespanStatsData,
            'exportedEventsCountByTimespanStatsData' => $exportedEventsCountByTimespanStatsData,
            'violationsCountByGate' => $violationsCountByGate,
            'approvedViolationsCountByGate' => $approvedViolationsCountByGate,
            'invalidViolationsCountByGate' => $invalidViolationsCountByGate,
            'exportedEventsCountByGate' => $exportedEventsCountByGate
                )
        );
    }

    public function actionEventsManagementExport() {

        access_denied_check("statistics");

        access_denied_check("statistics_events_management");

        header('Set-Cookie: fileDownload=true; path=/;');

        set_time_limit(60 * 60 * 1);

        $eventsStatisticsSearchForm = new EventsStatisticsSearchForm();

        $eventsStatisticsSearchForm->setAttributes($_POST['EventsStatisticsSearchForm'], false);

        $searchFilters = array();

        $validationResult = $eventsStatisticsSearchForm->validate();
        if (!$validationResult) {

            throw new CHttpException(400, Yii::t('app', 'Error While Validating FORM'));
        }

        $startDateTime = DateTime::createFromFormat(
                        getFormat_DateTime(), $eventsStatisticsSearchForm->startDateTime
        );

        $endDateTime = DateTime::createFromFormat(
                        getFormat_DateTime(), $eventsStatisticsSearchForm->endDateTime
        );

        $searchFilters['eventStartDateTime'] = $startDateTime;
        $searchFilters['eventEndDateTime'] = $endDateTime;

        if (!empty($eventsStatisticsSearchForm->gates)) {

            $searchFilters = array_merge($searchFilters, array('gates' => $eventsStatisticsSearchForm->gates)
            );
        }

        if (!empty($eventsStatisticsSearchForm->startTimeSlot) && !empty($eventsStatisticsSearchForm->endTimeSlot)) {

            $startTimeSlot = DateTime::createFromFormat(
                            getFormat_Time(), $eventsStatisticsSearchForm->startTimeSlot
            );

            $endTimeSlot = DateTime::createFromFormat(
                            getFormat_Time(), $eventsStatisticsSearchForm->endTimeSlot
            );

            $searchFilters = array_merge($searchFilters, array('timeSlot' => array(
                    'startTimeSlot' => $startTimeSlot,
                    'endTimeSlot' => $endTimeSlot
                )
                    )
            );
        }

        $eventsStatistics = EventsStatistics::model();

        $violationsManagementStatisticsByGatesCSV = $eventsStatistics->getViolationsManagementByGateStatisticsCSV($searchFilters);

        $csv = new ECSVExport($violationsManagementStatisticsByGatesCSV);
        $content = $csv->toCSV();

        $fileName = "Events_Management_By_Gates_From_";
        $fileName .= $startDateTime->format("Y_m_d_H_i_s");
        $fileName .= "_To_";
        $fileName .= $endDateTime->format("Y_m_d_H_i_s");
        $fileName .= ".csv";

        Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);

        exit();
    }

    public function actionOperatorsStatistics() {
        access_denied_check("statistics");

        access_denied_check("statistics_operators_statistics");

//        set_time_limit(3000);

        $gateModel = Gate::model();

        $gates = $gateModel->findAll();

        $approvedViolationsCountByTimespanStatsData = NULL;
        $invalidViolationsCountByTimespanStatsData = NULL;
        $usersApprovedViolationsCountByTimespanStatsData = NULL;
        $usersInvalidViolationsCountByTimespanStatsData = NULL;
        $validationDecisionsByTimespanStatsData = NULL;
        $usersValidationDecisionsByTimespanStatsData = NULL;

        $eventsStatisticsSearchForm = new EventsStatisticsSearchForm();
        if (isset($_POST['EventsStatisticsSearchForm'])) {

            $eventsStatisticsSearchForm->setAttributes($_POST['EventsStatisticsSearchForm'], false);

            $searchFilters = array();

            $validationResult = $eventsStatisticsSearchForm->validate();
            if (!$validationResult) {

                $this->render("operatorsStatistics/index", array(
                    'gates' => $gates,
                    'eventsStatisticsSearchForm' => $eventsStatisticsSearchForm,
                    'validationErrors' => $eventsStatisticsSearchForm->getErrors()
                        )
                );

                return;
            }

            $startDateTime = DateTime::createFromFormat(
                            getFormat_DateTime(), $eventsStatisticsSearchForm->startDateTime
            );

            $endDateTime = DateTime::createFromFormat(
                            getFormat_DateTime(), $eventsStatisticsSearchForm->endDateTime
            );

            if (!empty($eventsStatisticsSearchForm->gates)) {

                $searchFilters = array_merge($searchFilters, array('gates' => $eventsStatisticsSearchForm->gates)
                );
            }

            $gateFilter = "";

            if (array_key_exists("gates", $searchFilters)) {
                $gateFilter = " AND Gate IN (" . join(',', array_values($searchFilters["gates"])) . ")";
            }

//            $eventsStatistics = EventsStatistics::model();


            $queryString = "SELECT ID, ValidationTime, validation_result, ValidatedBy "
                    . "FROM storicotable "
                    . "where validation_result in ('approved','invalid') AND "
                    . "ValidationTime between '" . $startDateTime->format('Y-m-d H:i:s') . "' and '" . $endDateTime->format('Y-m-d H:i:s') . "'" . $gateFilter;


            $approvedViolationsCountByTimespanStatsData = array();
            $invalidViolationsCountByTimespanStatsData = array();
            $usersApprovedViolationsCountByTimespanStatsData = array();
            $usersInvalidViolationsCountByTimespanStatsData = array();
            $validationDecisionsByTimespanStatsData = array();
            $usersValidationDecisionsByTimespanStatsData = array();
            $userCommentsTempArray = array();

            $targetViolations = EventsStatistics::model()->findAllBySql($queryString);

            $userMap = array();
            foreach (User::model()->findAll() as $currentUser) {
                if (!array_key_exists($currentUser->id, $userMap)) {
                    $currentKeyToCreate = $currentUser->last_name . " " . $currentUser->first_name;
                    $userMap[$currentUser->id] = $currentUser->last_name . " " . $currentUser->first_name;
                    $usersApprovedViolationsCountByTimespanStatsData[$currentKeyToCreate] = 0;
                    $usersInvalidViolationsCountByTimespanStatsData[$currentKeyToCreate] = 0;
                    $userCommentsTempArray[$currentUser->id] = array();
                    $userCommentsTempArray[$currentUser->id][t('Approved Violations')] = 0;
                }
            }

            while ($startDateTime <= $endDateTime) {
                $approvedViolationsCountByTimespanStatsData[$startDateTime->format('Y-m-d')] = 0;
                $invalidViolationsCountByTimespanStatsData[$startDateTime->format('Y-m-d')] = 0;
                $startDateTime->modify("+1 day");
            }


            foreach ($targetViolations as $currentViolation) {
                $currentKey = $currentViolation->ValidationTime->format('Y-m-d');
                $currentUser = $userMap[$currentViolation->ValidatedBy];
                $currentComment = trim($currentViolation->eventBehaviors[0]->comment);
                $currentComment = strlen($currentComment) > 0 ? $currentComment : "Nessun commento";
                switch ($currentViolation["validation_result"]) {
                    case "approved":
//                        if (array_key_exists($currentKey, $approvedViolationsCountByTimespanStatsData)) {
                        $approvedViolationsCountByTimespanStatsData[$currentKey] += 1;
//                        } else {
//                            $approvedViolationsCountByTimespanStatsData[$currentKey] = 1;
//                        }
//                        if (array_key_exists($currentUser, $usersApprovedViolationsCountByTimespanStatsData)) {
                        $usersApprovedViolationsCountByTimespanStatsData[$currentUser] += 1;
//                        } else {
//                            $usersApprovedViolationsCountByTimespanStatsData[$currentUser] = 1;
//                        }

                        $userCommentsTempArray[$currentViolation->ValidatedBy][t('Approved Violations')] += 1;
                        break;
                    case "invalid":
//                        if (array_key_exists($currentKey, $invalidViolationsCountByTimespanStatsData)) {
                        $invalidViolationsCountByTimespanStatsData[$currentKey] += 1;
//                        } else {
//                            $invalidViolationsCountByTimespanStatsData[$currentKey] = 1;
//                        }
//                        if (array_key_exists($currentUser, $usersInvalidViolationsCountByTimespanStatsData)) {
                        $usersInvalidViolationsCountByTimespanStatsData[$currentUser] += 1;
//                        } else {
//                            $usersInvalidViolationsCountByTimespanStatsData[$currentUser] = 1;
//                        }
////                        if (strlen($currentComment) > 0) {
//                        if (array_key_exists($currentComment, $validationDecisionsByTimespanStatsData)) {
                        $validationDecisionsByTimespanStatsData[$currentComment] += 1;
//                        } else {
//                            $validationDecisionsByTimespanStatsData[$currentComment] = 1;
//                        }
                        
                        if(is_array($userCommentsTempArray[$currentViolation->ValidatedBy]))
                        {
                            if (array_key_exists($currentComment, $userCommentsTempArray[$currentViolation->ValidatedBy])) {
                                $userCommentsTempArray[$currentViolation->ValidatedBy][$currentComment] += 1;
                            } else {
                                $userCommentsTempArray[$currentViolation->ValidatedBy][$currentComment] = 1;
                            }
                        }
//                        }

                        break;
                }
            }

            foreach ($userCommentsTempArray as $currentUserId => $currentUserCommentsArray) {
                $usersValidationDecisionsByTimespanStatsData[] = array(
                    "user" =>
                    array(
                        "name" => $userMap[$currentUserId],
                        "id" => $currentUserId),
                    "data" => $currentUserCommentsArray);
            }

//  		$approvedViolationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByValidationDateTime(
//  			$startDateTime, $endDateTime, array_merge($searchFilters,
//  				array(
//  					'approvedViolations' => TRUE
//  				)
//  			)
//  		);
//  		
//  		$invalidViolationsCountByTimespanStatsData = $eventsStatistics->getViolationsCountByValidationDateTime(
//  			$startDateTime, $endDateTime, array_merge($searchFilters,
//  				array(
//  					'invalidViolations' => TRUE
//  				)
//  			)
//  		);
//            $usersApprovedViolationsCountByTimespanStatsData = $eventsStatistics->getUsersViolationsCountByValidationDateTime(
//                    $startDateTime, $endDateTime, array_merge($searchFilters, array(
//                'approvedViolations' => TRUE
//                            )
//                    )
//            );
//
//            $usersInvalidViolationsCountByTimespanStatsData = $eventsStatistics->getUsersViolationsCountByValidationDateTime(
//                    $startDateTime, $endDateTime, array_merge($searchFilters, array(
//                'invalidViolations' => TRUE
//                            )
//                    )
//            );
//
//            $validationDecisionsByTimespanStatsData = $eventsStatistics->getValidationDecisionsByValidationDateTime(
//                    $startDateTime, $endDateTime, $searchFilters);
//
//            $usersValidationDecisionsByTimespanStatsData = $eventsStatistics->getUsersValidationDecisionsByValidationDateTime(
//                    $startDateTime, $endDateTime, $searchFilters);
        }


//        print_r($gates);
//        echo '<br><br>';
//        print_r($eventsStatisticsSearchForm);
//        echo '<br><br>';
//        print_r($approvedViolationsCountByTimespanStatsData);
//        echo '<br><br>';
//        print_r($usersApprovedViolationsCountByTimespanStatsData);
//        echo '<br><br>';
//        print_r($usersInvalidViolationsCountByTimespanStatsData);
//        echo '<br><br>';
//        print_r($invalidViolationsCountByTimespanStatsData);
//        echo '<br><br>';
//        print_r($validationDecisionsByTimespanStatsData);
//        echo '<br><br>';
//        print_r($usersValidationDecisionsByTimespanStatsData);
//        echo '<br><br>';
//        die();

        $this->render("operatorsStatistics/index", array(
            'gates' => $gates,
            'eventsStatisticsSearchForm' => $eventsStatisticsSearchForm,
            'approvedViolationsCountByTimespanStatsData' => $approvedViolationsCountByTimespanStatsData,
            'usersApprovedViolationsCountByTimespanStatsData' => $usersApprovedViolationsCountByTimespanStatsData,
            'usersInvalidViolationsCountByTimespanStatsData' => $usersInvalidViolationsCountByTimespanStatsData,
            'invalidViolationsCountByTimespanStatsData' => $invalidViolationsCountByTimespanStatsData,
            'validationDecisionsByTimespanStatsData' => $validationDecisionsByTimespanStatsData,
            'usersValidationDecisionsByTimespanStatsData' => $usersValidationDecisionsByTimespanStatsData
                )
        );
    }

    public function actionExport(array $gates, array $vehiclesClass, $startTimestamp, $endTimestamp, $minSpeed, $maxSpeed, $granularity, $startTime, $endTime) {
        access_denied_check("statistics");
        header('Set-Cookie: fileDownload = true;path = /');

        set_time_limit(60 * 60 * 1);

        $statsQuery = new StatsQuery();
        $dataProvider = $statsQuery->getStatsData(
                array(
                    'vehiclesClass' => $vehiclesClass,
                    'gates' => $gates,
                    'startTimestamp' => $startTimestamp,
                    'endTimestamp' => $endTimestamp,
                    'minSpeed' => $minSpeed,
                    'maxSpeed' => $maxSpeed,
                    'granularity' => $granularity,
                    'useJoin' => true,
                    'startTime' => $startTime,
                    'endTime' => $endTime,
                )
        );

        $csv = new ECSVExport($dataProvider);
        $content = $csv->toCSV();

        $startDateTime = new DateTime();
        $startDateTime->setTimestamp($startTimestamp);

        $endDateTime = new DateTime();
        $endDateTime->setTimestamp($endTimestamp);

        $startTimeStr = str_replace(":", "_", $startTime);
        $endTimeStr = str_replace(":", "_", $endTime);

        $fileName = "Stats_from_" . $startDateTime->format("Y_m_d") . "_" . $startTimeStr . "_to_" . $endDateTime->format("Y_m_d") . "_" . $endTimeStr . ".csv";

        Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);

        exit();
    }

    public function actionExportDetailed(array $gates, array $vehiclesClass, $startTimestamp, $endTimestamp, $minSpeed, $maxSpeed, $granularity, $startTime, $endTime) {
        access_denied_check("statistics");
        header('Set-Cookie: fileDownload = true; path = /');

        set_time_limit(60 * 60 * 1);

        $statsQuery = new StatsQuery();
        $dataProvider = $statsQuery->getStatsData(
                array(
                    'vehiclesClass' => $vehiclesClass,
                    'gates' => $gates,
                    'startTimestamp' => $startTimestamp,
                    'endTimestamp' => $endTimestamp,
                    'minSpeed' => $minSpeed,
                    'maxSpeed' => $maxSpeed,
                    'granularity' => $granularity,
                    'splitByGate' => true,
                    'splitByClass' => true,
                    'useJoin' => true,
                    'startTime' => $startTime,
                    'endTime' => $endTime,
                )
        );

        $csv = new ECSVExport($dataProvider);
        $content = $csv->toCSV();

        $startDateTime = new DateTime();
        $startDateTime->setTimestamp($startTimestamp);

        $endDateTime = new DateTime();
        $endDateTime->setTimestamp($endTimestamp);

        $startTimeStr = str_replace(":", "_", $startTime);
        $endTimeStr = str_replace(":", "_", $endTime);

        $fileName = "Stats_from_" . $startDateTime->format("Y_m_d") . "_" . $startTimeStr . "_to_" . $endDateTime->format("Y_m_d") . "_" . $endTimeStr . ".csv";

        Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);

        exit();
    }

    public function actionDangerousGoodsFilter(array $gates, $startTimestamp, $endTimestamp, $startTime, $endTime) {
        access_denied_check("statistics");
        $statsQuery = new DangerousGoodsFromEventStatsQuery();
        $dataProvider = $statsQuery->getStatsData(
                array(
                    'gates' => $gates,
                    'startTimestamp' => $startTimestamp,
                    'endTimestamp' => $endTimestamp,
                    'startTime' => $startTime,
                    'endTime' => $endTime,
                )
        );

        $graphData = DangerousGoodsStatGraphEncoder::encode($dataProvider->getData(), 'kemler', 'Counter');
        $this->renderPartial('dangerousGoods/_results', array('dataProvider' => $dataProvider, 'graphData' => $graphData));
    }

    public function actionDangerousGoodsExport(array $gates, $startTimestamp, $endTimestamp, $startTime, $endTime) {
        header('Set-Cookie: fileDownload = true; path = /');

        set_time_limit(60 * 60 * 1);

        $statsQuery = new DangerousGoodsFromEventStatsQuery();
        $dataProvider = $statsQuery->getStatsData(
                array(
                    'gates' => $gates,
                    'startTimestamp' => $startTimestamp,
                    'endTimestamp' => $endTimestamp,
                    'startTime' => $startTime,
                    'splitByGate' => true,
                    'useJoin' => true,
                    'endTime' => $endTime,
                    'descriptions' => true,
                )
        );

        $csv = new ECSVExport($dataProvider);
        $content = $csv->toCSV();

        $startDateTime = new DateTime();
        $startDateTime->setTimestamp($startTimestamp);

        $endDateTime = new DateTime();
        $endDateTime->setTimestamp($endTimestamp);

        $startTimeStr = str_replace(":", "_", $startTime);
        $endTimeStr = str_replace(":", "_", $endTime);

        $fileName = "Stats_from_" . $startDateTime->format("Y_m_d") . "_" . $startTimeStr . "_to_" . $endDateTime->format("Y_m_d") . "_" . $endTimeStr . ".csv";

        Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);

        exit();
    }

    public function actionDangerousGoodsExportDetailed(array $gates, $startTimestamp, $endTimestamp, $startTime, $endTime) {
        access_denied_check("statistics");
        header('Set-Cookie: fileDownload = true; path = /');

        set_time_limit(60 * 60 * 1);

        $statsQuery = new DangerousGoodsFromEventStatsQuery();
        $dataProvider = $statsQuery->getStatsData(
                array(
                    'gates' => $gates,
                    'startTimestamp' => $startTimestamp,
                    'endTimestamp' => $endTimestamp,
                    'startTime' => $startTime,
                    'endTime' => $endTime,
                    'descriptions' => true,
                    'splitByGate' => true,
                    'splitByHour' => true,
                    'useJoin' => true,
                )
        );

        $csv = new ECSVExport($dataProvider);
        $content = $csv->toCSV();

        $startDateTime = new DateTime();
        $startDateTime->setTimestamp($startTimestamp);

        $endDateTime = new DateTime();
        $endDateTime->setTimestamp($endTimestamp);

        $startTimeStr = str_replace(":", "_", $startTime);
        $endTimeStr = str_replace(":", "_", $endTime);

        $fileName = "Stats_from_" . $startDateTime->format("Y_m_d") . "_" . $startTimeStr . "_to_" . $endDateTime->format("Y_m_d") . "_" . $endTimeStr . ".csv";

        Yii::app()->getRequest()->sendFile($fileName, $content, "text/csv", false);

        exit();
    }

}
