<?php

namespace CleantalkSP\SpbctWP\FSWatcher;

use CleantalkSP\SpbctWP\FSWatcher\Dto\FSWatcherParams;
use CleantalkSP\SpbctWP\FSWatcher\Scan\Scan;
use CleantalkSP\SpbctWP\FSWatcher\Analyzer\Analyzer;
use CleantalkSP\Variables\Post;

class Controller
{
    /**
     * @var bool
     */
    public static $debug;

    const STATUS_STOPPED = 'stopped';

    const STATUS_RUNNING = 'running';

    /**
     * @var \CleantalkSP\SpbctWP\FSWatcher\Storage\FileStorage::class
     */
    public static $storage;

    private static $status = self::STATUS_STOPPED;

    /**
     * @var FSWatcherParams
     */
    private static $params;

    public function __construct(FSWatcherParams $params)
    {
        self::$params = $params;
        $is_fs_watcher_action = Post::get('action') === 'spbct_fswatcher_compare' ||
            Post::get('action') === 'spbct_fswatcher_view_file' ||
            Post::get('action') === 'spbct_fswatcher_create_snapshot';

        if ( defined('DOING_AJAX') && DOING_AJAX && $is_fs_watcher_action) {
            $this->checkRateLimit();
        }
        add_action('wp_ajax_spbct_fswatcher_compare', [$this, 'compare']);
        add_action('wp_ajax_spbct_fswatcher_view_file', [$this, 'viewFile']);
        add_action('wp_ajax_spbct_fswatcher_create_snapshot', [$this, 'createSnapshot']);
    }

    /**
     * Initialize the `$debug` property false|true
     *
     * @return void
     */
    private static function getDebugState()
    {
        if ( defined('SPBC_FSWATCHER_DEBUG') ) {
            self::$debug = (bool) SPBC_FSWATCHER_DEBUG;
        }
    }

    /**
     * Scanning file system handler
     *
     * @param $params
     * @return void
     */
    protected static function run($params)
    {
        self::$status = self::STATUS_RUNNING;
        Scan::run($params);
        self::stop();
    }

    /**
     * This is the init method.
     *
     * Making initialize the `$debug` property
     *
     * Contains Ajax handler for requests:
     * 1) Comparing logs
     * 2) Scanning file system
     * 3) Automatically making ajax requests for 2)
     *
     * @param $params
     * @return void
     */
    public static function work()
    {
        global $spbc;
        self::getDebugState();

        if (self::$debug) {
            Logger::setSaltValue($spbc->data['salt']);
        }

        Service::setStorage(self::$params->storage);
    }

    /**
     * Scanning file system stop trigger
     *
     * @return void
     */
    private static function stop()
    {
        self::$status = self::STATUS_STOPPED;
        Service::setAllJournalsAsCompleted();
    }

    private function checkRateLimit()
    {
        if ( ! Service::isRateLimitPass() ) {
            echo json_encode(array('error' => 'Rate limit exceeded. Protected - Security by CleanTalk.'));
            die();
        }
    }

    public static function compare()
    {
        spbc_check_ajax_referer('spbc_secret_nonce', 'security');
        if (self::$debug) {
            Logger::log('run compare file system logs');
        }
        $compare_result = Analyzer::getCompareResult();
        header('Content-Type: application/json');
        if (false === $compare_result) {
            if (self::$debug) {
                Logger::log('Can not compare logs');
            }
            echo json_encode(array('error' => 'Can not compare logs'));
        } else {
            echo json_encode($compare_result);
        }
        die();
    }

    public function viewFile()
    {
        spbc_check_ajax_referer('spbc_secret_nonce', 'security');
        if (self::$debug) {
            Logger::log('run view file method');
        }

        header('Content-Type: application/json');
        try {
            $view_file = Analyzer::getViewFile();
            echo json_encode(array("data" => $view_file));
        } catch (\Exception $e) {
            if (self::$debug) {
                Logger::log('Can not view file');
            }
            echo json_encode(array('error' => 'Can not view file. ' . $e->getMessage()));
        }
        die();
    }

    public function createSnapshot()
    {
        spbc_check_ajax_referer('spbc_secret_nonce', 'security');
        if (self::$debug) {
            Logger::log('run scan file system');
        }
        self::run(self::$params);
        header('Content-Type: application/json');
        die(json_encode(['OK']));
    }
}
