<?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'])
        );
        $this->grav['twig']->twig()->addFilter(
            new \Twig_SimpleFilter('translations', [$this, 'getTranslationsOfPage'])
        );
    }

    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;
    }

//    public function getPage($route)
//    {
//        $page = null;
////        $translation_path = $page->path() . DS . $page_name_without_ext . '.' . $language . '.md';
//        if (file_exists($translation_path)) {
//            $page = new Page();
//            $page->init(new \SplFileInfo($page_path), $language . '.md');
//        }
//
//        return $page;
//    }

    public function getTranslationsOfPage(Page $page)
    {
        $languages = $this->config->get('system.languages.supported');
//        die(print_r($languages));
        $route_suffix = $page->rawRoute();
        $translations = array();
        $current_language = $page->language();

        $page_name_without_ext = substr($page->name(), 0, -(strlen($page->extension())));
        foreach ($languages as $language) {
//            $route = '/' . $language . $route_suffix;
//            $route = $route_suffix;

            // FIXME: nope. language-selector does this the hard way, by instantiating Page objects
            //$translation = $page->find($route);

            // … so we're falling back on the old school too
            $translation_path = $page->path() . DS . $page_name_without_ext . '.' . $language . '.md';
            if (file_exists($translation_path)) {
                $translation = new Page();
                $translation->init(new \SplFileInfo($translation_path), $language . '.md');
//                $translated_pages[$language] = $translation;
            } else {
                continue;
            }


//            var_dump($route);
//            die(var_dump($route));
//            die(var_dump($translation));
            if ($language == $current_language) {
                array_unshift($translations, $translation);
            } else {
                array_push($translations, $translation);
            }
        }

//        die(var_dump($translations));

        return $translations;
    }
}
