/* global Ext, ViewStateManager, App */
Ext.define( 'App.ux.StatefulTabPanel', {
  extend: 'Ext.tab.Panel',
  alias: 'widget.statefultabpanel',
  initComponent: function()
  {
    this.iconCls = this.iconCls || this.itemId;
    this.on( 'afterrender', this.onAfterRender, this);

    this.callParent( arguments);
  },

  setActiveTab: function( tab, dontUpdateHistory)
  {
    this.callParent( arguments);

    if (!dontUpdateHistory)
    {
      ViewStateManager.change( tab.itemId);
    }
  },

  addViewState: function( tab, path)
  {
    var i, item, newPath;

    for (i = 0; i < tab.items.length; i++)
    {
      item = tab.items.get( i);
      newPath = Ext.Array.clone( path);
      newPath.push( item);

      ViewStateManager.add( item.itemId, newPath);

      if (item instanceof App.ux.StatefulTabPanel)
      {
        this.addViewState( item, newPath);
      }
    }

    tab.viewStateDone = true;
  },

  onAfterRender: function( tab)
  {
    if (!tab.viewStateDone)
    {
      if (tab.ownerCt instanceof App.ux.StatefulTabPanel)
      {
        tab = tab.ownerCt;
      }

      this.addViewState( tab, []);
    }
  }
});