Ext.define("IceCap.view.Emulator", {

	xtype: "icecap-emulator",

	extend: "Ext.panel.Panel",

	layout: "fit",

	stateful: true,

	stateId: "icecep-emulator",

	requires: [
		"IceCap.controller.Emulator",
		"IceCap.view.Main"
	],

	config: {
		tabArea: null,
		toolBar: null,
		theme: "",
		scale: 14
	},

	controller: "icecap.controller.emulator",

	listeners: {
		onAddWebContainer: "onAddWebContainer"
	},

	stateEvents: [
		"add",
		"remove",
		"tabchange",
		"stateupdate"
	],

	initComponent: function() {

		var i_self = this;
		i_self.callParent(arguments);
		i_self.add(i_self.createTabArea());
		i_self.addDocked(i_self.createToolbar());
	},

	createTabArea: function() {

		var i_self = this;

		var i_tabpanel = Ext.widget("tabpanel", {
			layout: "fit",
			listeners: {
				add: {
					fn: "onStateNotify"
				},
				remove: {
					fn: "onStateNotify"
				},
				tabchange: {
					fn: "onStateNotify"
				}
			}
		});

		i_self.setTabArea(i_tabpanel);

		return i_tabpanel;
	},

	createToolbar: function() {

		var i_self = this;

		var i_controller = i_self.getController();

		var i_toolbar = Ext.widget("toolbar", {
			dock: "top",
			items: [
				{
					xtype: "button",
					text: "New session",
					handler: function() {

						i_controller.onNewSession();
					}
				}
			]
		});

		i_self.setToolBar(i_toolbar);

		return i_toolbar;
	},

	getState: function() {

		var i_self = this;

		var i_tabpanel = i_self.getTabArea();

		var o_state = {
			tabs: [],
			activeTabIndex: -1
		};

		var a_items = i_tabpanel.items.getRange();

		Ext.Array.each(a_items, function(i_panel) {

			var o_data = {};

			if (i_panel) {
				Ext.apply(o_data, i_panel.getState());
			}

			o_state.tabs.push(o_data);
		});

		if (a_items.length > 0) {
			o_state.activeTabIndex = i_tabpanel.items.indexOf(i_tabpanel.getActiveTab());
		}

		return o_state;
	},

	applyState: function(o_state) {

		var i_self = this;

		var i_controller = i_self.getController();

		var i_tabpanel = i_self.getTabArea();

		Ext.applyIf(o_state, {
			tabs: [],
			activeTabIndex: -1
		});

		var a_items = [];

		if (o_state.tabs.length > 0) {

			Ext.Array.each(o_state.tabs, function(o_config) {

				var o_panel = Ext.apply({
					title: "Icecap",
					closable: true,
					theme: i_self.getTheme(),
					scale: i_self.getScale()
				}, o_config.appConfig);

				var i_icecapPanel = Ext.widget("icecap-panel", o_panel);

				a_items.push(i_icecapPanel);
			});

			i_tabpanel.add(a_items);

			i_tabpanel.setActiveTab(o_state.activeTabIndex);
		}
		else {
			i_controller.onNewSession();
		}
	}
});
