<?php

class ThemeMakersTaxonomyTermTypes {

    //This initializes the hooks to allow saving of the
    public static function on_load($taxonomies = array()) {
        add_action('created_term', array(__CLASS__, 'term_type_update'), 10, 3);
        add_action('edit_term', array(__CLASS__, 'term_type_update'), 10, 3);
        //*****

        add_filter('manage_edit-cons_columns', array('ThemeMakersTaxonomyTermTypes', 'draw_cons_columns'));
        add_filter('manage_cons_custom_column', array('ThemeMakersTaxonomyTermTypes', 'draw_cons_columns_data'), 5, 3);


        if (!empty($taxonomies)) {
            foreach ($taxonomies as $taxonomy) {
                self::register_taxonomy($taxonomy);
            }
        }
    }

    public static function draw_cons_columns() {
        $columns = array(
            "cb" => "<input type=\"checkbox\" />",
            "name" => __("Name", THEMEMAKERS_THEME_FOLDER_NAME),
            "description" => __("Description", THEMEMAKERS_THEME_FOLDER_NAME),
            "slug" => __("Slug", THEMEMAKERS_THEME_FOLDER_NAME),
            "console_color" => __("Color", THEMEMAKERS_THEME_FOLDER_NAME),
            "posts" => __("Posts", THEMEMAKERS_THEME_FOLDER_NAME),
        );

        return $columns;
    }

    public static function draw_cons_columns_data($value = '', $column_name = '', $term_id = 0) {
        switch ($column_name) {
            case "console_color":
                $color = get_taxonomy_term_type('cons', $term_id);
                echo '<span style="display:inline-block; width:12px; height:12px; background:' . $color . '"></span>&nbsp;' . $color;
                break;
        }
    }

    public static function register_taxonomy($taxonomy) {
        if (!is_array($taxonomy))
            $taxonomy = array($taxonomy);
        foreach ($taxonomy as $tax_name) {
            add_action("{$tax_name}_edit_form_fields", array(__CLASS__, "edit_form_fields"), 10, 2);
        }
    }

    static function edit_form_fields($term, $taxonomy) {
        $console_color = get_taxonomy_term_type($taxonomy, $term->term_id);
        $html = '
<tr class="form-field form-required">
  <th scope="row" valign="top"><label for="tag-type">' . __('Console Color', THEMEMAKERS_THEME_FOLDER_NAME) . '</label></th>
  <td><input type="text" name="console_color" value="' . $console_color . '" class="colorpicker_input"></td>
</tr>';

        //*******


        echo $html;
    }

    // These hooks are called after adding and editing to save $_POST['tag-term']
    public static function term_type_update($term_id, $tt_id, $taxonomy) {
        if (isset($_POST['console_color'])) {
            update_taxonomy_term_type($taxonomy, $term_id, $_POST['console_color']);
        }
    }

}
