<?php

namespace Sync\Controller;

use App\Controller\App;

class Sync extends App {

    protected function before() {

        if (!$this->isAllowed('sync/manage')) {
            return $this->stop(401);
        }
    }

    public function index() {

        $jobs = $this->module('sync')->jobs();
        $isRunning =  $this->helper('sync')->isSyncRunning();

        $targets = \array_filter($this->app->dataStorage->getKey('cockpit', 'sync.targets', []), function($target) {
            return $target['modes']['pull'] || $target['modes']['push'];
        });

        return $this->render('sync:views/index.php', \compact('jobs', 'targets', 'isRunning'));
    }

    public function settings() {

        $targets = $this->app->dataStorage->getKey('cockpit', 'sync.targets', []);
        $syncKey = $this->module('sync')->syncKey();

        return $this->render('sync:views/settings.php', \compact('targets', 'syncKey'));
    }

    public function save() {

        $this->hasValidCsrfToken(true);

        $targets = $this->param('targets', null);

        if (!isset($targets)) {
            return false;
        }

        $this->app->dataStorage->setKey('cockpit', 'sync.targets', $targets);

        return ['success' => true];
    }

    public function collect() {

        $return = [
            'data' => [],
            'assets' => [],
        ];

        $collections = $this->app->dataStorage->lstCollections();

        foreach ($collections as $collection) {
            $return['data'][$collection] = $this->app->dataStorage->count($collection);
        }

        return $return;
    }

    public function run() {

        $this->helper('session')->close();
        $this->hasValidCsrfToken(true);

        $isRunning = $this->helper('sync')->isSyncRunning();

        if ($isRunning) {
            return ['message' => 'Sync job is already running'];
        }

        $config = $this->param('config');

        if (!isset($config['target'], $config['jobs'])) {
            return false;
        }

        $this->helper('async')->exec('Cockpit()->helper("sync")->run($target, $jobs);', [
            'target' => $config['target'],
            'jobs' => $config['jobs'],
        ]);

        return ['success' => 1];
    }

    public function getSyncLog() {

        $this->helper('session')->close();

        return ['log' => $this->helper('sync')->log()];
    }

    public function reset() {
        $this->helper('sync')->stop();
        $this->app->reroute('/sync');
    }
}
