<?php

class Hook_comcode_roller
{
    public function get_tag()
    {
        return array(
            'tag_title' => 'Dice Roller',
            'tag_description' => 'Produce a random dice roll.',
            'tag_example' => '[roller="some_id"]1,2,3,4,5,6[/roller]',
            'tag_tag' => 'roller',
            'tag_replace' => array($this, 'tag_replace'),
            'tag_parameters' => 'param',
            'tag_block_tag' => 0,
            'tag_textual_tag' => 0,
            'tag_dangerous_tag' => 0,
        );
    }

    public function tag_replace($embed, $map)
    {
        $id = empty($map['param']) ? get_page_name() : $map['param'];
        $_embed = $embed->evaluate();

        $cache_bucket_id = fix_id('roller_' . $id . '_' . $_embed);

        $cached = get_value($cache_bucket_id, null, true);
        if ($cached !== null) {
            return make_string_tempcode(escape_html($cached));
        }

        $matches = array();
        if (preg_match('#^(\d+)d(\d+)$#', $_embed, $matches) == 0) {
            // Pick from a set style...

            if (!empty($_embed)) {
                $rand_options = array_map('trim', explode(',', $_embed));
            } else {
                $rand_options = array('1', '2', '3', '4', '5', '6');
            }

            shuffle($rand_options);

            $output = $rand_options[0];
        } else {
            // xdy format (where x is number of rolls and y is number of dice faces)...

            $num_rolls = intval($matches[1]);
            $num_faces = intval($matches[2]);

            $output = '';

            for ($i = 0; $i < $num_rolls; $i++) {
                if ($output != '') {
                    $output .= ' & ';
                }

                $output .= strval(mt_rand(1, $num_faces));
            }
        }

        if (!running_script('preview')) {
            set_value($cache_bucket_id, $output, true);
        }

        return make_string_tempcode(escape_html($output));
    }
}