<?php
/**
 * @file
 * Allows users to add PGN chess games to content using pgn4web.
 */

/**
 * Implements hook_init().
 *
 * - Add pgn4web javascript settings (location of pgn4web.js script & pages).
 */
function pgn4web_init() {
  $config = pgn4web_get_global_config();
  $settings = array(
    'path'  => libraries_get_path('pgn4web', TRUE),
    'query' => drupal_http_build_query($config),
  );
  drupal_add_js(array('pgn4web' => $settings), 'setting');
}

/**
 * Implements hook_menu().
 *
 * - Global configuration at admin/config/content/pgn4web.
 */
function pgn4web_menu() {
  $items = array();

  $items['admin/config/content/pgn4web'] = array(
    'title'            => 'pgn4web',
    'description'      => 'Configure the default look and feel of the pgn4web PGN viewer.',

    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('pgn4web_global_settings_form'),

    'access callback'  => 'user_access',
    'access arguments' => array('administer site configuration'),

    'file'             => 'pgn4web.admin.inc',
  );

  return $items;
}

/**
 * Get global configuration of look & feel.
 *
 * @param $defaults
 *   Boolean.  If TRUE, return the builtin defaults.
 *
 * @return
 *   Array.
 */
function pgn4web_get_global_config($defaults = FALSE) {
  // These are the recommended parameters:
  // See: http://code.google.com/p/pgn4web/wiki/User_Notes_drupal
  $default_config = array(
    'am'   => 'l',      // autoplayMode=game|loop|none
    'd'    => '3000',   // delay=nn (ms)

    'ss'   => '26',     // squareSize=nn (px)
    'ps'   => 'd',      // pieceSize=default|nn (px)
    'pf'   => 'd',      // pieceFont=alpha|merida|uscf|random|default
    'hm'   => 'b',      // highlightMode=border|square|none

    'bd'   => 'c',      // buttonsDisplay=hidden|standard|custom
    'hd'   => 'j',      // headerDisplay=justified|centered|hidden|live|variations
    'md'   => 'f',      // movesDisplay=figurine|text|puzzle|hidden

    'tm'   => '13',     // textMargin=...
    'fhs'  => '14',     // fontHeaderSize=nn (px)
    'fms'  => '14',     // fontMovesSize=nn (px)
    'fcs'  => 'm',      // fontCommentsSize=moves|nn (px)
    'cd'   => 'i',      // commentsDisplay=hidden|inline|newline
    'fp'   => '13',     // framePadding=...

    'hl'   => 't',      // horizontalLayout=true|false
    'fh'   => 'b',      // frameHeight=board|page|...
    'fw'   => 'p',      // frameWidth=board|page|...

    'lch'  => 'EFF4EC', // lightColorHex=###
    'dch'  => 'C6CEC3', // darkColorHex=###
    'bbch' => '000000', // boardBorderColorHex=###
    'hch'  => 'DAF4D7', // highlightColorHex=###

    'cbch' => 'F0F0F0', // controlBackgroundColorHex=default|###
    'ctch' => '000000', // controlTextColorHex=###

    'fhch' => '000000', // fontHeaderColorHex=###
    'fmch' => '000000', // fontMovesColorHex=###
    'fcch' => '808080', // fontCommentsColorHex=###
    'hmch' => 'DAF4D7', // highlightMoveColorHex=###

    'bch'  => 'FFFFFF', // backgroundColorHex=transparant|###

    // These are not specified:
    'bsch' => 't',      // boardShadowColorHExt=transparant|border|###
    'fvch' => 'c',      // fontVariationsColorHex=comments|###
  );

  // If we need the defaults, return.
  if ($defaults) {
    return $default_config;
  }

  // Make sure only known parameters are set and that all have a value.
  $config = variable_get('pgn4web-global', array());
  $config = array_intersect_key($config, $default_config);
  $config += $default_config;

  return $config;
}

/**
 * Implements hook_xbbcode_info().
 */
function pgn4web_xbbcode_info() {
  $tags = array();

  $tags['pgn'] = array(
    'callback' => 'pgn4web_xbbcode_pgn_render',
    'options' => array(
      'nocode' => TRUE,
      'plain'  => TRUE,
    ),
    'sample' => '[pgn height=500 initialHalfmove=16 autoplayMode=none]
[Event "World championship"]
[Site "Moscow URS"]
[Date "1985.10.15"]
[Round "16"]
[White "Karpov"]
[Black "Kasparov"]
[Result "0-1"]

1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nb5 d6 6. c4 Nf6 7. N1c3 a6 8.
Na3 d5 9. cxd5 exd5 10. exd5 Nb4 11. Be2 Bc5 12. O-O O-O 13. Bf3 Bf5 14.
Bg5 Re8 15. Qd2 b5 16. Rad1 Nd3 17. Nab1 h6 18. Bh4 b4 19. Na4 Bd6 20. Bg3
Rc8 21. b3 g5 22. Bxd6 Qxd6 23. g3 Nd7 24. Bg2 Qf6 25. a3 a5 26. axb4 axb4
27. Qa2 Bg6 28. d6 g4 29. Qd2 Kg7 30. f3 Qxd6 31. fxg4 Qd4+ 32. Kh1 Nf6 33.
Rf4 Ne4 34. Qxd3 Nf2+ 35. Rxf2 Bxd3 36. Rfd2 Qe3 37. Rxd3 Rc1 38. Nb2 Qf2
39. Nd2 Rxd1+ 40. Nxd1 Re1+ 0-1
[/pgn]',
    'description' => 'PGN chess game(s).',
  );

  return $tags;
}

/**
 * XBBCode callback.
 */
function pgn4web_xbbcode_pgn_render($tag, $xbbcode_filter) {
  // Store the HTML5 data-attributes we need to add.
  $attributes = array();

  // TODO: we need some input-checking here on the $value!
  foreach ((array)$tag->attrs as $attr => $value) {
    switch (drupal_strtolower($attr)) {
      case 'layout':
      case 'l':
        $attributes['data-pgn4web-l'] = $value;
        break;

      case 'height':
      case 'h':
        $attributes['data-pgn4web-h'] = $value;
        break;

      case 'initialgame':
      case 'ig':
        $attributes['data-pgn4web-ig'] = $value;
        break;

      case 'initialvariation':
      case 'iv':
        $attributes['data-pgn4web-iv'] = $value;
        break;

      case 'initialhalfmove':
      case 'ih':
        $attributes['data-pgn4web-ih'] = $value;
        break;

      case 'autoplaymode':
      case 'am':
        $attributes['data-pgn4web-am'] = $value;
        break;

      case 'showmoves':
      case 'sm':
        $attributes['data-pgn4web-sm'] = $value;
        break;

      case 'pgndata':
      case 'pd':
        $attributes['data-pgn4web-pd'] = $value;
        break;

      default:
        // Other attributes are ignored. This is similar to the WordPress plugin:
        // http://code.google.com/p/pgn4web/wiki/User_Notes_wordpress
        break;
    }
  }

  // Add class-attribute.
  $attributes['class'] = 'pgn4web';

  //TODO: if pgnData is specified, maybe provide a link to the PGN file instead of
  // displaying the tag content.
  return '<pre' . drupal_attributes($attributes) . '>' . $tag->content . '</pre>';
}

/**
 * Implements hook_libraries_info().
 */
function pgn4web_libraries_info() {
  $libraries = array();

  $libraries['pgn4web'] = array(
    'name'         => 'pgn4web',
    'vendor url'   => 'http://pgn4web.casaschi.net',
    'download url' => 'http://code.google.com/p/pgn4web/downloads/list',

    'version arguments' => array(
      'file'    => 'pgn4web.js',
      'pattern' => "@var pgn4web_version = '([0-9\.]+)';@",
    ),

    'files' => array(
      'js' => array(
        'pgn4web.js',
      ),
    ),
  );

  return $libraries;
}

