<?php

require_once 'globals.php';

class ExportViolationsStatsCommand extends CConsoleCommand {

    public function run($args) {
        echo "\n######################################################################";
        echo "\n##                                                                  ##";
        echo "\n##                    Export violations stats                       ##";
        echo "\n##                                                                  ##";
        echo "\n######################################################################";
        echo "\n";
        echo "\n";

        echoln("Searching for workperiods to export...");
        $workPeriods = WorkPeriod::model()->to_register()->findAll();
        $nFoundWP = count($workPeriods);
        echoln("Found $nFoundWP workperiods. Export in progress...");
        $currentWP = 1;
        foreach ($workPeriods as $wp) {
            echoln("Processing workperiod $currentWP of $nFoundWP...");
            $currentWP++;
            $report = new Report (); // approved and invalid

            $report->initByWorkPeriod($wp, false);

            if ($this->registerExportCounters($report->repository->all, $wp->user, $wp->report_generation_date, $wp->id, 0)) {
                $wp->confirmRegistration();
                $wp->save();
            }
        }

        echoln("Searching for services to export...");
        $services = Service::model()->to_register()->findAll();
        $nFoundServices = count($services);
        echoln("Found $nFoundWP services. Export in progress...");
        $currentService = 1;
        foreach ($services as $sw) {
            echoln("Processing service $currentService of $nFoundServices...");
            $currentService++;
            $report = new Report (); // approved and invalid
            $report->initByService($sw, false);

            if ($this->registerExportCounters($report->repository->all, $sw->registerOperator, $sw->report_generation_date, 0, $sw->ID)) {
                $sw->confirmRegistration();
                $sw->save();
            }
        }

        echoln("Command completed.");

        return 0;
    }

    protected function registerExportCounters($events, $user, $ext_code_time, $id_work_period, $id_service) {
        if (count($events) <= 0)
            return true;

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

        foreach ($gates as $gate) {
            $gateConters[$gate->Gate]['description'] = $gate->Descrizione;
            $gateConters[$gate->Gate]['exported'] = 0;
            $gateConters[$gate->Gate]['gate_sn'] = $gate->Gate;
            $gateConters[$gate->Gate]['gate_type'] = $gate->GateType;
            $gateConters[$gate->Gate]['gate_model'] = $gate->device_model;
            $gateConters[$gate->Gate]['deleted'] = 0;
            $gateConters[$gate->Gate]['plate_changed'] = 0;
            $gateConters[$gate->Gate]['min_ext_code'] = 0;
            $gateConters[$gate->Gate]['max_ext_code'] = 0;
        }

        $gateConters[$event->Gate]['deleted'] = 0;
        $gateConters[$event->Gate]['plate_changed'] = 0;
        $gateConters[$event->Gate]['min_ext_code'] = 0;
        $gateConters[$event->Gate]['max_ext_code'] = 0;
        $gateConters[$event->Gate]['num_of_events'] = 0;

        foreach ($events as $event) {
            if ($event->ext_code != ExtCode::NULL_EXT_CODE) {
                $gateConters[$event->Gate]['exported'] += 1;

                if ($gateConters[$event->Gate]['min_ext_code'] === 0) {
                    $gateConters[$event->Gate]['min_ext_code'] = $event->ext_code;
                    $gateConters[$event->Gate]['max_ext_code'] = $event->ext_code;
                } else {
                    $gateConters[$event->Gate]['min_ext_code'] = min($event->ext_code, $gateConters[$event->Gate]['min_ext_code']);
                    $gateConters[$event->Gate]['max_ext_code'] = max($event->ext_code, $gateConters[$event->Gate]['max_ext_code']);
                }
            }

            if ($event->ext_code == ExtCode::NULL_EXT_CODE)
                $gateConters[$event->Gate]['deleted'] += 1;

            if (!isEmpty($event->ExtPlate) && $event->ExtPlate != $event->Plate)
                $gateConters[$event->Gate]['plate_changed'] += 1;

            $gateConters[$event->Gate]['num_of_events'] += 1;
        }



        $eventReg = EventServerRegistration::model()->byMe()->find();

        if (isEmpty($eventReg))
            return false;


        $resSave = true;

        foreach ($gateConters as $gateC) {
            if ($gateC['num_of_events'] > 0) {
                if ($id_work_period > 0)
                    $expExisting = ExportedEvents::model()->byServer($eventReg->id)->byGate($gateC['gate_sn'])->byWorkPeriod($id_work_period)->count();
                else
                    $expExisting = ExportedEvents::model()->byServer($eventReg->id)->byGate($gateC['gate_sn'])->byService($id_service)->count();

                if ($expExisting > 0) {
                    if ($id_work_period > 0)
                        $expEv = ExportedEvents::model()->byServer($eventReg->id)->byGate($gateC['gate_sn'])->byWorkPeriod($id_work_period)->find();
                    else
                        $expEv = ExportedEvents::model()->byServer($eventReg->id)->byGate($gateC['gate_sn'])->byService($id_service)->find();

                    $expEv->export_time = $ext_code_time;
                    $expEv->exported_events = $gateC['exported'];
                    $expEv->deleted_events = $gateC['deleted'];
                    $expEv->plate_changes = $gateC['plate_changed'];
                    $expEv->min_ext_code = $gateC['min_ext_code'];
                    $expEv->max_ext_code = $gateC['max_ext_code'];
                    $expEv->id_event_server = $eventReg->id;
                    $expEv->user_name = $user->first_name . " " . $user->last_name;
                    $expEv->gate_sn = $gateC['gate_sn'];
                    $expEv->gate_type = $gateC['gate_type'];
                    $expEv->gate_model = $gateC['gate_model'];
                    $expEv->gate_description = $gateC['description'];
                    $expEv->validated_events = $gateC['num_of_events'];
                    $expEv->id_work_period = $id_work_period;
                    $expEv->id_service = $id_service;
                    $expEv->id_report = $id_report;

                    if (!$expEv->save())
                        $resSave = false;
                }
                else {

                    $expEv = new ExportedEvents;

                    $expEv->export_time = $ext_code_time;
                    $expEv->exported_events = $gateC['exported'];
                    $expEv->deleted_events = $gateC['deleted'];
                    $expEv->plate_changes = $gateC['plate_changed'];
                    $expEv->min_ext_code = $gateC['min_ext_code'];
                    $expEv->max_ext_code = $gateC['max_ext_code'];
                    $expEv->id_event_server = $eventReg->id;
                    $expEv->user_name = $user->first_name . " " . $user->last_name;
                    $expEv->gate_sn = $gateC['gate_sn'];
                    $expEv->gate_type = $gateC['gate_type'];
                    $expEv->gate_model = $gateC['gate_model'];
                    $expEv->gate_description = $gateC['description'];
                    $expEv->validated_events = $gateC['num_of_events'];
                    $expEv->id_work_period = $id_work_period;
                    $expEv->id_service = $id_service;
                    $expEv->id_report = $id_report;

                    if (!$expEv->save())
                        $resSave = false;
                }
            }
        }

        return $resSave;
    }

}
