// --------------------------------------------------------------------
// wm3d - A Flash Molecular Viewer
//
// Copyright (c) 2011-2013, tamanegi (tamanegi@users.sourceforge.jp)
// All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// --------------------------------------------------------------------

// Manager class for action; preregistered commands by <ACTION> tags
// For example, rotation, scaling, translation can be registered

/**
  Manager of ACTIONs
**/
class WMActionMgr {
  /**
    actions
  **/
  private var __actions:Array< WMAction >;
  /**
    loop or not
  **/
  @:isVar public var loop( get, set ):Bool;
    /**
      getter of `loop`
    **/
    public function get_loop():Bool { return( loop ); }
    /**
      setter of `loop`
    **/
    public function set_loop( f:Bool ) {
      loop = f;
      return( loop );
    }

  /**
    current index of action
  **/
  @:isVar public var cur( get, null ):Int;
    /**
      getter of cur
    **/
    public function get_cur():Int { return( cur ); }

  // ####################################################################
  /**
    Constructor
  **/
  public function new() {
    cur = -1;
    loop = false;
    __actions = new Array< WMAction >();
  }

  /**
    load from Xml
  **/
  public function loadXml( ?nd:Xml = null ) {
    if ( nd == null ) return;
    // check attributes
    __loadXmlAttributes( nd );
    for ( ndc in nd.elements() ) {
      if ( ndc.nodeName.toUpperCase() == "ACTION" ) {
        var ac:WMAction = new WMAction( ndc );
        __actions.push( ac );
      }
    }
  }

  /**
    whether action is registered
  **/
  public function isEmpty():Bool { return( ( __actions.length == 0 ) ); }

  /**
    read attribute of element AMGR
  **/
  private function __loadXmlAttributes( ?nd:Xml = null ) {
    if ( nd == null ) return;
    if ( nd.exists( "loop" ) ) {
      // if loop > 0, activate loop
      loop = ( Std.parseInt( nd.get( "loop" ) ) > 0 );
    }
  }

  /**
    get next action
  **/
  public function getNextAction():WMAction {
    cur++;
    // push back when looping
    if ( cur == __actions.length && loop ) cur = 0;
    return( getCurrentAction() );
  }

  /**
    get current action
  **/
  public function getCurrentAction():WMAction {
    // if no action remains, return null
    if ( cur < 0 || cur >= __actions.length ) return( null );
    return( __actions[cur] );
  }
}
