<?php

use dokuwiki\Extension\Event;

/**
 * Class helper_plugin_confmanager
 */
class helper_plugin_confmanager extends DokuWiki_Plugin {

    /**
     * Get all registered config managers
     *
     * @return ConfigManagerConfigType[]
     */
    public function getConfigFiles() {
        static $configs = null;
        if ($configs === null) {
            $configs = [];
            Event::createAndTrigger('CONFMANAGER_CONFIGFILES_REGISTER', $configs, null, false);
            usort($configs, [$this, '_sortByConfigName']);
        }
        return $configs;
    }

    /**
     * Get a specific config manager
     *
     * @param string $id Config ID
     * @return ConfigManagerConfigType|false
     */
    public function getConfigById($id) {
        foreach ($this->getConfigFiles() as $config) {
            if ($this->getConfigId($config) === $id) {
                return $config;
            }
        }
        return false;
    }

    /**
     * Get the id of a config manager
     *
     * @param ConfigManagerConfigType $config
     * @return string
     */
    public function getConfigId(ConfigManagerConfigType $config) {
        $hash = '';
        $paths = $config->getPaths();
        if (count($paths) == 0) return '';

        $hash .= realpath($paths[0]);
        return md5($hash);
    }

    /**
     * @param string[] $files
     * @return bool
     */
    public function areWriteable($files) {
        foreach ($files as $file) {
            if (!is_writable($file)) {
                return false;
            }
        }
        return true;
    }

    /**
     * @param string $file      filename path to file
     * @param string $content
     */
    public function saveFile($file, $content) {
        $success = io_saveFile($file, $content);
        if ($success !== false ) {
            msg($this->getLang('changes applied'), 1);
        } elseif (!is_writable($file)) {
            msg($this->getLang('error:saving failed not writable'), -1);
        } else {
            msg($this->getLang('error:saving failed'), -1);
        }

    }

    /**
     * Get header for config files created by confmanager
     *
     * @return string
     */
    public function getCoreConfigHeader() {
        return "# This config was generated by the confmanager plugin.\n"
             . "# Changes made to this file may be overwritten by the plugin.\n"
             . "# Please use the confmanager in the Dokuwiki admin interface.\n";
    }

    /**
     * @param string $k1
     * @param string $k2
     * @return int
     */
    public function _sortConf( $k1 , $k2 ) {
        return strlen( $k2 ) - strlen( $k1 );
    }

    /**
     * @param string $k1
     * @param string $k2
     * @return int
     */
    public function _sortHuman( $k1 , $k2 ) {
        $k1 = strtolower($k1);
        $k2 = strtolower($k2);
        return strnatcmp($k1,$k2);
    }

    /**
     * Compare config managers by name
     *
     * @param ConfigManagerConfigType $left
     * @param ConfigManagerConfigType $right
     * @return int
     */
    public function _sortByConfigName(ConfigManagerConfigType $left, ConfigManagerConfigType $right) {
        return strnatcasecmp($left->getName(), $right->getName());
    }

    public function tplSaveButton() {
        static $called = false;
        if ($called) {
            return;
        }
        include DOKU_PLUGIN . 'confmanager/tpl/formControls.php';
        $called = true;
    }

    /**
     * Prepare entity for saving
     *
     * @param string $str
     * @return string
     */
    public function prepareEntity($str) {
        $str = trim($str);
        $str = str_replace("\n", '', $str);
        $str = str_replace("\r", '', $str);
        $str = str_replace('#', '\\#', $str);
        return $str;
    }
}

