var _ = require('../../../lib/alloy/underscore')._,
	U = require('../../../utils'),
	CU = require('../compilerUtils'),
	CONST = require('../../../common/constants');

exports.parse = function(node, state) {
	return require('./base').parse(node, state, parse);
};

function parse(node, state, args) {
	var children = U.XML.getElementsFromNodes(node.childNodes),
		arrayName = CU.generateUniqueId(),
		code = '',
		isSearchBar = false,
		hasRows = false,
		searchBarName;

	if (args.collection) {
		var tableState = require('./default').parse(node, state);
		code += tableState.code;

		// iterate through all children
		var itemCode = '';
		for (var i = 0, l = children.length; i < l; i++) {
			var child = children[i],
				childArgs = CU.getParserArgs(child);

			// validate children of tableview

			itemCode += CU.generateNode(child, {
				parent: {},
				styles: state.styles,
				post: function(node, state, args) {
					return 'rows.push(' + state.parent.symbol + ');\n';
				}
			});
		}

		// create fetch handler
		var col = 'Alloy.Collections[\'' + args.collection + '\']';
		code += col + ".on('fetch', function(e) { ";
		code += "	var len = " + col + ".models.length;";
		code += "	var rows = [];";
		code += "	for (var i = 0; i < len; i++) {";
		code += "		var " + CONST.MODEL_VAR + " = " + col + ".models[i];";
		code += itemCode;
		code += "	}";
		code += tableState.parent.symbol + ".setData(rows);";
		code += "});";
	} else {
		code = 'var ' + arrayName + ' = [];\n';

		// iterate through all children
		for (var i = 0, l = children.length; i < l; i++) {
			var child = children[i],
				childArgs = CU.getParserArgs(child);

			// make sure we are dealing with rows and sections
			if (childArgs.fullname === 'Alloy.Require') {
				var inspect = CU.inspectRequireNode(child);
				_.each(inspect.names, function(name) {
					if (name === 'Ti.UI.TableViewRow' ||
						name === 'Ti.UI.TableViewSection') {
						isSearchBar = false;
					} else if (name === 'Ti.UI.SearchBar') {
						isSearchBar = true;
					} else {
						U.die('TableView <Require> child at position ' + i + ' has elements that are not rows, sections, or SearchBar');
					}
				});
			} else if (childArgs.fullname === 'Ti.UI.TableViewRow' ||
					   childArgs.fullname === 'Ti.UI.TableViewSection') {
				isSearchBar = false;
			} else if (childArgs.fullname === 'Ti.UI.SearchBar') {
				isSearchBar = true;
			} else {
				U.die('TableView child at position ' + i + ' is not a row or section, or a <Require> containing rows, sections, or SearchBar');
			}

			// generate code for the row/section/searchbar
			code += CU.generateNode(child, {
				parent: {},
				styles: state.styles,
				post: function(node, state, args) {
					if (isSearchBar) {
						searchBarName = state.parent.symbol;
					} else {
						hasRows = true;
						return arrayName + '.push(' + state.parent.symbol + ');\n';
					}
				}
			});
		}

		// Create the initial TableView code
		var extras = [];
		if (hasRows) { extras.push(['data', arrayName]); }
		if (searchBarName) { extras.push(['search', searchBarName]) }
		if (extras.length) { state.extraStyle = CU.createVariableStyle(extras); }

		var tableState = require('./default').parse(node, state);
		code += tableState.code;
	}

	// Update the parsing state
	return {
		parent: {},
		styles: state.styles,
		code: code
	}
};

@@ -391,16 +391,54 @@
 ueId(),%0A
+%09%09localModel = CU.generateUniqueId(),%0A
 %09%09code =
@@ -442,16 +442,16 @@
 e = '',%0A
-
 %09%09isSear
@@ -797,16 +797,22 @@
 ;%0A%0A%09%09%09//
+ TODO:
  validat
@@ -884,32 +884,72 @@
 %09%09%09%09parent: %7B%7D,%0A
+%09%09%09%09local: true,%0A%09%09%09%09model: localModel,%0A
 %09%09%09%09styles: stat
@@ -1099,16 +1099,17 @@
 handler%0A
+%0A
 %09%09var co
@@ -1360,23 +1360,18 @@
 %22 + 
-CONST.MODEL_VAR
+localModel
  + %22

use local variables and pass model via state for TableView binding