<?php
namespace Grav\Plugin;

use Grav\Common\Page\Page;
use Grav\Common\Plugin;

/**
 * Features:
 * - /sync   Cheap git-sync (did not knew about it at the time)
 *
 * 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;
        }

        // /sync
        $uri = $this->grav['uri'];
        $route = $this->config->get('plugins.m3-p2.route');
        if ($route && $route == $uri->path()) {
            $this->enable([
                'onPageInitialized' => ['onSyncPageInitialized', 0]
            ]);
        }

        $this->enable([
            'onTwigInitialized' => ['setupWebIdeUrl', 0],
        ]);
    }

    /**
     * Sync with the sources.
     */
    public function onSyncPageInitialized()
    {
        // shell cwd is project root

        $out = "Opening a fortune cookie…\n\n\n";
//        $out .= shell_exec("fortune | cowsay -e Oø -f dragon") . "\n";
        $out .= shell_exec("fortune") . "\n\n";

        $out .= "Trying to sync content with GitLab…\n\n\n";
        $out .= shell_exec("cd user/pages && git pull --rebase --autostash origin master 2>&1") . "\n";

        $out .= "Done.";

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

    public function setupWebIdeUrl()
    {
        $this->grav['twig']->twig()->addFilter(
            new \Twig_SimpleFilter('webide_url', [$this, 'getWebIdeUrlForPage'])
        );
    }

    public function getWebIdeUrlForPage(Page $page)
    {
        $url = "https://m3p2.ljbac.com/-/ide/project/m3p2/courses/edit/master/-/";
        $url .= substr($page->filePathClean(), 11); // 11==strlen('/user/pages')

        return $url;
    }
}
