<?php

class SystemUpdateCronJob extends AbstractCronJob
{

    public function run()
    {
        $data = SystemUpdate::getUpdateFileDataFromServer();

        if (!empty($data)) {
            $sort = 0;
            foreach ($data as $key => $value) {
                $this->saveSystemUpdate($key, $value, $sort);
                $sort++;
            }
            $this->saveSystemUpdate('timestamp', PhonalisaDate::newServerTimestamp(), $sort++);
        } else {
            Log::e("Can't find update.json", 'SystemUpdateCronJob');
        }

        if (cfg('AUTO_SYSTEM_UPDATE') === '1' && $this->systemNeedUpdate()) {
            Log::v('Start auto system upgrade', 'SystemUpdateCronJob');
            PhonalisaCtrldConnector::runSystemUpgrade(cfg('AUTO_SYSTEM_UPDATE'));
            SystemUpdate::createUpdateDoneAlert();
        }
    }

    public function getCronRule()
    {
        return cfg('UPDATE_CRON_JOB');
    }

    protected function saveSystemUpdate($key, $value, $sort)
    {
        $model = SystemUpdate::model()->findByAttributes(array('descr' => $key));

        if (!$model) {
            $model = new SystemUpdate();
        }
        $model->descr = $key;
        $model->value = $value;
        $model->sort = $sort;
        $model->save();
    }

    protected function systemNeedUpdate()
    {
        if (!PhonalisaCtrldConnector::hasConnection()) {
            Log::e('Could not connect to Ctrld!', 'SystemUpdateCronJob');
            return false;
        }

        $result = false;
        $ctrld = PhonalisaCtrldConnector::getSystemVersion();
        if (isset($ctrld->status) && isset($ctrld->version)) {
            if ($ctrld->status === 'error') {
                Log::e('' . @$ctrld->errorText, 'SystemUpdateCronJob');
            } else {
                if (SystemUpdate::serverVersionNewerThanSystem($ctrld->version)) {
                    Log::v('New updates are available!', 'SystemUpdateCronJob');
                    $result = true;
                } else {
                    Log::v('System is up-to-date', 'SystemUpdateCronJob');
                }
            }
        } else {
            Log::e('Call to unknown function!', 'SystemUpdateCronJob');
        }
        return $result;
    }
}
