<?php
/**
 * Schema form pane, this is required for building
 * faster and scalable schema form panes with ajax.
 *
 * @see VTCore_Zeus_Panels_Style
 * @see VTCore_Wordpress_Element_WpAccordion
 * @see VTCore_Wordpress_Ajax_Processor_WpAccordion
 * @author jason.xie@victheme.com
 *
 */
class VTCore_Zeus_Schema_Pane 
extends VTCore_Bootstrap_Element_BsElement {

  protected $context = array(
    'activeSchemaID' => false,
    'schemaKey' => false,
    'title' => false,
    'description' => false,
    'schemas' => array(),
    'processors' => array(
      'post' => 'VTCore_Form_Post',
    ),
  );

  private $fontOptionsMarkup;
  private $grids = array(
    'columns' => array(
      'mobile' => 12,
      'tablet' => 3,
      'small' => 3,
      'large' => 3,
    ),
  );

  private $activeSchemaID;
  private $value;
  private $name;
  private $text;
  private $schema;
  
  public function buildElement() {

    // Register all available fonts first
    $this->buildFontOptions();

    $this
      ->addChildren(new VTCore_Bootstrap_Element_BsHeader(array(
        'tag' => 'h3',
        'text' => $this->getContext('title'),
      )))
      ->addChildren(new VTCore_Bootstrap_Form_BsDescription(array(
        'text' => $this->getContext('description'),
      )))
      ->addChildren(new VTCore_Bootstrap_Grid_BsRow());

    $this->schema = new VTCore_Zeus_Schema_Factory();

    foreach ($this->getContext('schemas') as $elkey => $value) {

      $this->text = str_replace('-', ' ', ucfirst($elkey));
      $this->name = 'theme[schemas][' . $this->getContext('activeSchemaID') . '][color][' . $this->getContext('schemaKey') . '][' . $elkey . ']';

      // Always get data from factory, the value from context might be outdated
      $this->value = $this->schema->getActiveSchema()->getColorValue($this->getContext('schemaKey'), $elkey);

      // Build color form
      if (strpos($elkey, 'color') !== false
        || strpos($elkey, '-hover') !== false
        || strpos($elkey, '-focus') !== false
        || strpos($elkey, '-visited') !== false) {

        $this->buildColorForm();

      }

      // Build image form
      elseif (strpos($elkey, 'image') !== false) {
        $this->buildImageForm();
      }

      // Build background repeat form
      elseif (strpos($elkey, 'background-repeat') !== false) {
        $this->buildBackgroundRepeatForm();
      }

      // Build border style form
      elseif (strpos($elkey, 'border-style') !== false) {
        $this->buildBorderStyleForm();

      }

      // Build font style form
      elseif (strpos($elkey, 'font-style') !== false
        || strpos($elkey, 'heading-style') !== false) {
        $this->buildFontStyleForm();
      }

      // Build form weight form
      elseif (strpos($elkey, 'weight') !== false) {
        $this->buildFontWeightForm();
      }

      // Build form family form
      elseif (strpos($elkey, 'family') !== false) {
        $this->buildFontFamilyForm();
      }

      // Build gradient form
      elseif (strpos($elkey, 'background-gradient') !== false) {
        $this->buildGradientForm();
      }

      // fallback to standard text form
      else {
        $this->buildStandardTextForm();
      }
    }


    // Free Memory
    $this->schema = null;

  }

  /**
   * Method for building the schema font options with
   * google fonts and normal fonts
   */
  private function buildFontOptions() {

    $this->fontOptionsMarkup = get_transient('vtcore_zeus_style_panel_font_options');

    if (empty($this->fontOptionsMarkup)) {
      $options = array(
        '' => __('Not set', BASE_THEME),
        "georgia, serif" => "Georgia",
        "'palatino linotype', 'Book Antiqua', serif" => "Palatino",
        "times new romans, times, serif" => "Times new romans",
        "arial, helvetica, sans-serif" => "Arial",
        "'arial black', gadget, sans-serif" => "Arial Black",
        "'comic sans ms', cursive, sans-serif" => "Comic Sans",
        "impact, charcoal, sans-serif" => "Impact",
        "'lucida sans unicode', 'Lucida Grande', sans-serif" => "Lucida",
        "tahoma, geneva, san-serif" => "Tahoma",
        "'trebuchet ms', helvetica, sans-serif" => "Trebuchet MS",
        "verdana, geneva, sans-serif" => "Geneva",
        "'courier new', courier, monospace" => "Courier",
        "'lucida console', monaco, monospace" => "Lucida",
      );

      $options += VTCore_Wordpress_Init::getFactory('fonts')->getOptions();

      $object = new VTCore_Form_Select(array(
        'name' => 'placeholder',
        'options' => $options,
      ));

      // Crazy way to inject markup directly for
      // saving expensive cost while building
      // the whole google fonts array.
      // @todo remove this and replace with better
      //       form element!
      $this->fontOptionsMarkup = $object->__toString();
      $this->fontOptionsMarkup = strip_tags($this->fontOptionsMarkup, '<option>');

      unset($object);
      unset($options);

      set_transient('vtcore_zeus_style_panel_font_options', $this->fontOptionsMarkup, 12 * HOUR_IN_SECONDS);
    }

    return $this;
  }


  /**
   * Building a valid css color selector form
   * @return VTCore_Zeus_Panels_Style
   */
  private function buildColorForm() {

    $this
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Form_BsColor(array(
        'text' => $this->text,
        'name' => $this->name,
        'value' => $this->value,
        'grids' => $this->grids,
      )));

    return $this;
  }




  /**
   * Building a valid wp image selector form
   * @return VTCore_Zeus_Panels_Style
   */
  private function buildImageForm() {
    $this
      ->lastChild()
      ->addChildren(new VTCore_Wordpress_Form_WpMedia(array(
        'text' => $this->text,
        'name' => $this->name,
        'value' => $this->value,
        'grids' => $this->grids,
      )));

    return $this;
  }




  /**
   * Building a valid background repeat selector form
   * @return VTCore_Zeus_Panels_Style
   */
  private function buildBackgroundRepeatForm() {
    $this
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Form_BsSelect(array(
        'text' => $this->text,
        'name' => $this->name,
        'value' => $this->value,
        'options' => array(
          '' => __('Not set', BASE_THEME),
          'no-repeat' => __('No Repeat', BASE_THEME),
          'repeat' => __('Repeat All', BASE_THEME),
          'repeat-x' => __('Repeat Horizontally', BASE_THEME),
          'repeat-y' => __('Repeat Vertically', BASE_THEME),
        ),
        'grids' => $this->grids,
      )));

    return $this;
  }



  /**
   * Building a valid border style selector form
   * @return VTCore_Zeus_Panels_Style
   */
  private function buildBorderStyleForm() {
    $this
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Form_BsSelect(array(
        'text' => $this->text,
        'name' => $this->name,
        'value' => $this->value,
        'options' => array(
          '' => __('Not set', BASE_THEME),
          'none' => __('None', BASE_THEME),
          'inherit' => __('Inherit', BASE_THEME),
          'solid' => __('Solid', BASE_THEME),
          'dotted' => __('Dotted',BASE_THEME),
          'dashed' => __('Dashed', BASE_THEME),
          'double' => __('Double', BASE_THEME),
          'ridge' => __('Ridge', BASE_THEME),
          'inset' => __('Inset', BASE_THEME),
          'outset' => __('Outset', BASE_THEME),
          'groove' => __('Groove', BASE_THEME),
        ),
        'grids' => $this->grids
      )));

    return $this;
  }



  /**
   * Building a valid font style selector form
   * @return VTCore_Zeus_Panels_Style
   */
  private function buildFontStyleForm() {
    $this
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Form_BsSelect(array(
        'text' => $this->text,
        'name' => $this->name,
        'value' => $this->value,
        'options' => array(
          '' => __('Not set', BASE_THEME),
          'normal' => __('Normal', BASE_THEME),
          'oblique' => __('Oblique', BASE_THEME),
          'italic' => __('Italic', BASE_THEME),
          'inherit' => __('Inherit',BASE_THEME),
        ),
        'grids' => $this->grids,
      )));

    return $this;
  }




  /**
   * Building a valid font weight form selector
   * @return VTCore_Zeus_Panels_Style
   */
  private function buildFontWeightForm() {
    $this
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Form_BsSelect(array(
        'text' => $this->text,
        'name' => $this->name,
        'value' => $this->value,
        'options' => array(
          '' => __('Not set', BASE_THEME),
          'inherit' => __('Inherit',BASE_THEME),
          100 => __('Thin', BASE_THEME),
          200 => __('Extra light', BASE_THEME),
          300 => __('Light', BASE_THEME),
          400 => __('Normal', BASE_THEME),
          500 => __('Medium', BASE_THEME),
          600 => __('Demi bold', BASE_THEME),
          700 => __('Bold', BASE_THEME),
          800 => __('Heavy', BASE_THEME),
          900 => __('Black', BASE_THEME),
        ),
        'grids' => $this->grids
      )));

    return $this;
  }



  /**
   * Building a valid font family selector
   *
   * @note This is ugly but needed for faster page load!
   * @return VTCore_Zeus_Panels_Style
   */
  private function buildFontFamilyForm() {

    $this
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Form_BsSelect(array(
        'text' => $this->text,
        'name' => $this->name,
        'value' => $this->value,
        'grids' => $this->grids,
      )));

    // Force inject options directly using markup
    // Ugly but faster than rebuilding the whole options element
    if (isset($_POST)) {
      $key = str_replace(array('[', ']'), array('.', ''), $this->name);
      $value = VTCore_Utility::getArrayValueKeys($_POST, $key);

      if ($value) {
        $this->value = wp_unslash($value);
      }
    }

    $markup = str_replace('value="' . $this->value . '"', 'value="' . $this->value . '" selected', $this->fontOptionsMarkup);
    $this->lastChild()->lastChild()->lastChild()->setRaw(true)->setText($markup);

    return $this;
  }




  /**
   * Building a valid gradient selector form
   * @return VTCore_Zeus_Panels_Style
   */
  private function buildGradientForm() {
    $this
      ->lastChild()
      ->addChildren(new VTCore_Wordpress_Form_WpGradient(array(
        'name' => $this->name,
        'text' => $this->text,
        'value' => $this->value,
        'grids' => array(
          'columns' => array(
            'mobile' => 12,
            'tablet'=> 6,
            'small' => 6,
            'large' => 6,
          ),
        ),
      )));

    // Fix the default naming convention to match
    // the color shorthand rules
    foreach ($this->lastChild()->lastChild()->findChildren('type', 'input') as $object) {
      $oldName = $object->getAttribute('name');
      $object->addAttribute('name', str_replace('[gradient]', '', $oldName));
    }

    foreach ($this->lastChild()->lastChild()->findChildren('type', 'select') as $object) {
      $oldName = $object->getAttribute('name');
      $object->addAttribute('name', str_replace('[gradient]', '', $oldName));
    }

    unset($gradients);

    return $this;
  }



  /**
   * Building a valid standard text field form
   * @return VTCore_Zeus_Panels_Style
   */
  private function buildStandardTextForm() {
    $this
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Form_BsText(array(
        'text' => $this->text,
        'name' => $this->name,
        'value' => $this->value,
        'grids' => $this->grids,
      )));

    return $this;
  }

}