<?php

namespace MGModule\DNSManager2\controllers\addon\admin;

use \MGModule\DNSManager2 as main;
use \MGModule\DNSManager2\mgLibs\custom\helpers\TimeDiffHelper;
use \MGModule\DNSManager2\mgLibs\custom\manager\GlobalSettingHelper;
use \MGModule\DNSManager2\mgLibs\custom\TaskManager;
use \MGModule\DNSManager2\models\custom\globalsetting\GlobalSettingEnum;
use \MGModule\DNSManager2\models\custom\task\TaskStatusEnum;

class cron extends main\mgLibs\process\abstractController{

    private $default_tasks = array("LogCleaner:main", "NotificationCleaner:main", "Synchronization:main", "Cleaner:main","ZoneStatus:main", "Backupper:main");

    public function indexCRON($input, $vars = array()) {
        $this->checkIfDefaultTaskExists();

        $diff = TimeDiffHelper::diff(GlobalSettingHelper::getSetting(GlobalSettingEnum::CRON_LAST_RUN));
        GlobalSettingHelper::setSetting(GlobalSettingEnum::CRON_RUN_TIME_PERIOD, $diff->minutes);
        GlobalSettingHelper::setSetting(GlobalSettingEnum::CRON_LAST_RUN, date('Y-m-d H:i:s'));

        $main_tasks = TaskManager::getXTasksObjects(100, false, 0, array(TaskStatusEnum::START, TaskStatusEnum::IN_PROGRESS));



        foreach($main_tasks as $task)
        {
            $task->run();
        }

        return array();
    }

    private function checkIfDefaultTaskExists() {

        foreach($this->default_tasks as $task_name) {
            $task = TaskManager::getXTasksObjects(1, $task_name, 0, array(TaskStatusEnum::START, TaskStatusEnum::IN_PROGRESS));
            if(empty($task))
            {
                if($task_name ==='ZoneStatus:main' && count(main\mgLibs\custom\helpers\StatusHelper::getRows()))
                {
                    TaskManager::addTask($task_name);
                }
                elseif ($task_name !== 'ZoneStatus:main')
                {
                    TaskManager::addTask($task_name);
                }
            }
        }
    }
}
