<?php
namespace Grav\Plugin;

use Grav\Common\Page\Page;
use Grav\Common\Plugin;
use mysql_xdevapi\Exception;
use RocketTheme\Toolbox\Event\Event;

/**
 * Class M3P2Plugin
 * @package Grav\Plugin
 */
class M3P2Plugin extends Plugin
{
    /**
     * @return array
     *
     * The getSubscribedEvents() gives the core a list of events
     *     that the plugin wants to listen to. The key of each
     *     array section is the event that the plugin listens to
     *     and the value (in the form of an array) contains the
     *     callable (or function) as well as the priority. The
     *     higher the number the higher the priority.
     */
    public static function getSubscribedEvents()
    {
        return [
            'onPluginsInitialized' => ['onPluginsInitialized', 0]
        ];
    }

    /**
     * Initialize the plugin
     */
    public function onPluginsInitialized()
    {
        // Don't proceed if we are in the admin plugin
        if ($this->isAdmin()) {
            return;
        }

//        // Enable the main event we are interested in
//        $this->enable([
//            'onPageContentRaw' => ['onPageContentRaw', 0]
//        ]);



        $uri = $this->grav['uri'];
        $route = $this->config->get('plugins.m3-p2.route');
//        throw new \Exception($route." - ".$uri->path());

        if ($route && $route == $uri->path()) {
            $this->enable([
                'onPageInitialized' => ['onPageInitialized', 0]
            ]);
        }
    }

//    /**
//     * Do some work for this event, full details of events can be found
//     * on the learn site: http://learn.getgrav.org/plugins/event-hooks
//     *
//     * @param Event $e
//     */
//    public function onPageContentRaw(Event $e)
//    {
//        // Get a variable from the plugin configuration
//        $text = $this->grav['config']->get('plugins.m3-p2.text_var');
//
//        // Get the current raw content
//        $content = $e['page']->getRawContent();
//
//        // Prepend the output with the custom text and set back on the page
//        $e['page']->setRawContent($text . "\n\n" . $content);
//    }

    /**
     * Send user to a random page
     */
    public function onPageInitialized()
    {
        $out = "Trying to sync content with gitlab…\n";

        # shell pwd is project root
        $out .= shell_exec("cd user/pages && git pull --rebase origin master") . "\n";
        $out .= shell_exec("fortune | cowsay -e Oø -f dragon") . "\n";

        $out .= "Done.";

        die("<pre>".$out."</pre>");  // This is all I find to write to the page.
    }
}
