<?php
/**
 * @package CleverOgre
 * @subpackage OgreAlert
 * @since OgreAlert 0.1.8
 */

namespace OgreAlert;

if (!defined('ABSPATH')) exit;

class Display {

    public static function load() {
        if (is_admin()) return;

        add_action('wp', array(__CLASS__, 'init'));
    }

    static function init() {
        if (empty(\OgreAlert\Alert::get_active())) return;

        add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_scripts'));

        $position = \OgreAlert\Settings::get('message_position');
        switch ($position) {
            case 'top':
            case 'bottom':
            case 'footer':
                add_action('wp_footer', array(__CLASS__, 'display_alerts'));
                break;
            case 'custom':
                add_action('display_alerts', array(__CLASS__, 'display_alerts'));
                break;
        }
    }

    static function enqueue_scripts() {
        wp_enqueue_style('ogrealert', \OgreAlert\Settings::get('dir') . 'assets/sass/style.css', array(), \OgreAlert\Settings::get('version'), 'all');
        wp_enqueue_script('ogrealert', \OgreAlert\Settings::get('dir') . 'assets/js/frontend.js', array('jquery'), \OgreAlert\Settings::get('version'), true);
        wp_localize_script('ogrealert', 'ogrealert', array(
            'text_color' => \OgreAlert\Settings::get('message_text_color'),
            'background_color' => \OgreAlert\Settings::get('message_background_color'),
            'transition_duration' => intval(\OgreAlert\Settings::get('message_transition_duration')),
            'transition_animation' => \OgreAlert\Settings::get('message_transition_animation'),
        ));
    }

    static function display_alerts() {
        $ids = \OgreAlert\Alert::get_active();
        if (empty($ids)) return;

        self::load_template('loop-start');
        foreach ($ids as $id) {
            self::load_template('alert', \OgreAlert\Priority::get($id), true, array('id' => $id));
        }
        self::load_template('loop-end');
    }

    private static function load_template($filename, $filepart = '', $echo = true, $vars = array()) {
        $path = \OgreAlert\Settings::get('path') . 'templates/' . $filename . '-' . $filepart . '.php';
        if (!file_exists($path)) {
            $path = \OgreAlert\Settings::get('path') . 'templates/' . $filename . '.php';
            if (!file_exists($path)) {
                if ($echo) {
                    echo '';
                    return false;
                } else {
                    return '';
                }
            }
        }

        ob_start();
        extract($vars);
        include($path);
        $html = ob_get_contents();
        ob_end_clean();

        if ($echo) {
            echo $html;
            return true;
        } else {
            return $html;
        }
    }

}

\OgreAlert\Display::load();
