/*

Copyright 2008-2011 Clipperz Srl

This file is part of Clipperz's Javascript Crypto Library.
Javascript Crypto Library provides web developers with an extensive
and efficient set of cryptographic functions. The library aims to
obtain maximum execution speed while preserving modularity and
reusability.
For further information about its features and functionalities please
refer to http://www.clipperz.com

* Javascript Crypto Library is free software: you can redistribute
  it and/or modify it under the terms of the GNU Affero General Public
  License as published by the Free Software Foundation, either version
  3 of the License, or (at your option) any later version.

* Javascript Crypto Library is distributed in the hope that it will
  be useful, but WITHOUT ANY WARRANTY; without even the implied
  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the GNU Affero General Public License for more details.

* You should have received a copy of the GNU Affero General Public
  License along with Javascript Crypto Library.  If not, see
  <http://www.gnu.org/licenses/>.

*/

Clipperz.Base.module('Clipperz.PM.UI.iPhone.Controllers');

//	Some parts of this controller have been derived from the iUI library.

Clipperz.PM.UI.iPhone.Controllers.MainController = function() {
	this._loginForm =		null;
	this._cardList =		null;
	this._cachedValues =	null;
	this._user =			null;

	if (typeof window.onorientationchange == 'object') {
		MochiKit.Signal.connect(window, 'onorientationchange', this, 'orientationChangeHandler');
		MochiKit.Async.callLater(0, MochiKit.Base.method(this, 'orientationChangeHandler'));
	} else {
		this.setOrientation('portrait');
//		this.setOrientation('landscape');
	}

	this.addMetaTag('viewport', 'width=devicewidth; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;');
	this.addMetaTag('apple-mobile-web-app-capable', 'yes');
	this.addMetaTag('apple-mobile-web-app-status-bar-style', 'black');

	this.addLinkTag('apple-touch-icon', 'data:image/png;charset=utf-8;base64,[encoded data, 5584 characters]');
//	this.addLinkTag('apple-touch-startup-image', 'default.png');

//	if (!window.navigator.standalone)	// not running as an installed app

	MochiKit.Signal.connect(Clipperz.Signal.NotificationCenter, 'selectedDirectLogin', this, 'selectedDirectLoginHandler');

	MochiKit.DOM.addElementClass(document.body, 'iPhone');
	return this;
}

MochiKit.Base.update(Clipperz.PM.UI.iPhone.Controllers.MainController.prototype, {

	'toString': function () {
		return "Clipperz.PM.UI.iPhone.Controllers.MainController";
	},

	//=========================================================================

	'user': function () {
		return this._user;
	},
	
	'setUser': function (aValue) {
		this._user = aValue;
	},

	//=========================================================================

	'loginForm': function() {
		if (this._loginForm == null) {
			MochiKit.DOM.removeElement('mainDiv');
			this._loginForm = new Clipperz.PM.UI.iPhone.Components.LoginForm({element:MochiKit.DOM.currentDocument().body});
			MochiKit.Signal.connect(this._loginForm, 'doLogin', this, 'doLoginHandler')
		}
		
		return this._loginForm;
	},

	'removeLoginForm': function () {
		if (this._loginForm != null) {
			this._loginForm.remove();
			this._loginForm = null;
		}
	},

	//-----------------------------------------------------------------------------

	'cardList': function () {
		if (this._cardList == null) {
			this._cardList = new Clipperz.PM.UI.iPhone.Components.CardList({element:MochiKit.DOM.currentDocument().body});
			MochiKit.Signal.connect(this._cardList, 'searchEvent',	this, 'searchEventHandler')
			MochiKit.Signal.connect(this._cardList, 'selectedCard',	this, 'selecetedCardHandler')
		}
		
		return this._cardList;
	},

	//=========================================================================

	'currentWidth': function () {
		return this._currentWidth;
	},
	
	'setCurrentWidth': function (aValue) {
		this._currentWidth = aValue;
	},

	//=========================================================================

	'orientationChangeHandler': function () {
		switch(window.orientation) {
			case 0:
				this.setOrientation('portrait');
				break;  
			case 90:
			case -90: 
				this.setOrientation('landscape');
				break;
		}
	},

	//-------------------------------------------------------------------------

	'setOrientation': function (anOrientation) {
		document.body.setAttribute('orientation', anOrientation);
		setTimeout(scrollTo, 100, 0, 1);
	},

	//-------------------------------------------------------------------------

	'slidePages': function (fromPage, toPage, backwards) {        
		var axis;
		var slideDone;
		
		slideDone = function () {
	//		console.log("slideDone");
			if (!hasClass(toPage, "dialog")) {
				fromPage.removeAttribute("selected");
			}
			checkTimer = setInterval(checkOrientAndLocation, 300);
			setTimeout(updatePage, 0, toPage, fromPage);
			fromPage.removeEventListener('webkitTransitionEnd', slideDone, false);
		}

		axis = (backwards ? fromPage : toPage).getAttribute("axis");

		clearInterval(checkTimer);

		if (canDoSlideAnim() && axis != 'y') {
			slide2(fromPage, toPage, backwards, slideDone);
		} else {
			slide1(fromPage, toPage, backwards, axis, slideDone);
		}
	},

	//-------------------------------------------------------------------------

	'getCachedValues': function () {
		var deferredResult;

		if (this._cachedObjects != null) {
			deferredResult = MochiKit.Async.succeed(this._cachedObjects);
		} else {
			deferredResult = new Clipperz.Async.Deferred("MainController.getCachedValues", {trace:false});
			deferredResult.addMethod(this.user(), 'getRecords');
			deferredResult.addCallback(MochiKit.Base.map, Clipperz.Async.collectResults("MainController.getCachedValues - collectResults", {
				'_rowObject':			MochiKit.Async.succeed,
				'_reference':			MochiKit.Base.methodcaller('reference'),
				'label':				MochiKit.Base.methodcaller('label'),
				'favicon':				MochiKit.Base.methodcaller('favicon'),
				'_searchableContent':	MochiKit.Base.methodcaller('searchableContent')
			}, {trace:false}));
			deferredResult.addCallback(Clipperz.Async.collectAll);
			deferredResult.addCallback(MochiKit.Base.bind(function (someRows) {
				this._cachedObjects = someRows;
				return this._cachedObjects;
			}, this));
			deferredResult.callback();
		}
		
		return deferredResult;
	},
	//=========================================================================

	'run': function(shouldShowRegistrationForm) {
		this.loginForm().render();
		MochiKit.Async.callLater(1, MochiKit.Base.method(this.loginForm(), 'focusOnUsername'));
	},
	
	//=========================================================================

	'doLoginHandler': function (someArgs) {
		var deferredResult;
		var	parameters;
		var	shouldUseOTP;
//		var loginProgress;
		var	user;
		var getPassphraseDelegate;

		parameters = someArgs;
		shouldUseOTP = (typeof(parameters.passphrase) == 'undefined');

		getPassphraseDelegate = MochiKit.Base.partial(MochiKit.Async.succeed, parameters.passphrase);
		user = new Clipperz.PM.DataModel.User({'username':parameters.username, 'getPassphraseFunction':getPassphraseDelegate});

		deferredResult = new Clipperz.Async.Deferred("MainController.doLogin", {trace:false});
		deferredResult.addCallbackPass(MochiKit.Signal.signal, Clipperz.Signal.NotificationCenter, 'initProgress', {'steps':4});
		deferredResult.addMethod(this.loginForm(), 'showLoginProgress');
		deferredResult.addCallback(MochiKit.Async.wait, 0.1);
		deferredResult.addMethod(Clipperz.Crypto.PRNG.defaultRandomGenerator(), 'deferredEntropyCollection');
		deferredResult.addMethod(user, 'login');
		deferredResult.addMethod(this, 'setUser', user);
		deferredResult.addMethod(user, 'getRecords');
		deferredResult.addMethod(this, 'removeLoginForm');
		deferredResult.addMethod(this.cardList(), 'render');
		deferredResult.addMethod(this, 'displaySelectedRecords', '');
		deferredResult.addErrback(MochiKit.Base.method(this.loginForm(), 'showLoginError'));
		deferredResult.callback();

		return deferredResult;
	},

	//=========================================================================

	'searchEventHandler': function (aValue) {
//console.log("searching for ... " + aValue);
		return this.displaySelectedRecords(aValue);
	},

	//=========================================================================

	'_displaySelectedRows': function (aFilter, someRows) {
		var result;
		
		result = someRows;

		if (aFilter != null) {
			var filter;
			var	filterRegExp;
			
			filter = aFilter.replace(/[^A-Za-z0-9]/g, "\\$&");
			filterRegExp = new RegExp(filter, "i");
			result = MochiKit.Base.filter(function (aCachedResult) { return filterRegExp.test(aCachedResult['_searchableContent'])}, result);
		}


		result.sort(MochiKit.Base.partial(function (aKey, aComparator, aObject, bObject) {
			return aComparator(aObject[aKey], bObject[aKey]);
		}, 'label',  Clipperz.Base.caseInsensitiveCompare));

		this.cardList().update(result);
	},

	//-------------------------------------------------------------------------
	
	'displaySelectedRecords': function (aFilter) {
		return Clipperz.Async.callbacks("MainController.displaySelectedrows", [
			MochiKit.Base.method(this, 'getCachedValues'),
			MochiKit.Base.method(this, '_displaySelectedRows', aFilter)
		], {trace:false});
	},

	//=========================================================================

	'selecetedCardHandler': function (aRecordReference) {
		var	deferredResult;
		var	recordData;

		recordData = {};
//console.log("Showing detail for card with reference", aRecordReference);
		deferredResult = new Clipperz.Async.Deferred("MainController.selectedCardHandler", {trace:false});
		deferredResult.addMethod(this.user(), 'getRecord', aRecordReference);
		deferredResult.collectResults({
			'_reference':	MochiKit.Base.methodcaller('reference'),
			'title':		MochiKit.Base.methodcaller('label'),
			'favicon':		MochiKit.Base.methodcaller('favicon')
		});
		deferredResult.addCallback(function (someData) {
			MochiKit.Base.update(recordData, someData);
		})
		deferredResult.addMethod(this.cardList(), 'showCard', recordData);

		deferredResult.addMethod(this.user(), 'getRecord', aRecordReference);
		deferredResult.addMethodcaller('notes');
		deferredResult.addCallback(function (someNotes) {
			recordData['notes'] = someNotes;
		})

		deferredResult.addMethod(this.user(), 'getRecord', aRecordReference);
		deferredResult.addMethodcaller('getCurrentRecordVersion');
		deferredResult.addMethodcaller('fields');
		deferredResult.addCallback(MochiKit.Base.values);
		deferredResult.addCallback(MochiKit.Base.map, Clipperz.Async.collectResults("MainController.selectedCardHandler - fields", {
			'label':	MochiKit.Base.methodcaller('label'),
			'value':	MochiKit.Base.methodcaller('value'),
			'isHidden':	MochiKit.Base.methodcaller('isHidden')
		}, {trace:false}));
		deferredResult.addCallback(Clipperz.Async.collectAll);
		deferredResult.addCallback(function (someData) {
			recordData['fields'] = someData;
		});

		deferredResult.addMethod(this.user(), 'getRecord', aRecordReference);
		deferredResult.addMethodcaller('directLogins');
		deferredResult.addCallback(MochiKit.Base.values);
		deferredResult.addCallback(MochiKit.Base.map, Clipperz.Async.collectResults("MainController.selectedCardHandler - directLogins", {
			'label':		MochiKit.Base.methodcaller('label'),
			'favicon':		MochiKit.Base.methodcaller('favicon'),
			'_reference':	MochiKit.Base.methodcaller('reference')
		}, {trace:false}));
		deferredResult.addCallback(Clipperz.Async.collectAll);
		deferredResult.addCallback(function (someData) {
			recordData['directLogins'] = someData;
		});

		deferredResult.addMethod(this.cardList(), 'showCardDetails', recordData);
		deferredResult.callback();
		
		return deferredResult;
	},

	//=========================================================================

	'selectedDirectLoginHandler': function (someData) {
		var	deferredResult;

//console.log("<<< signal - directLogin");
		deferredResult = new Clipperz.Async.Deferred("MainController.selectedDirectLoginHandler", {trace:false});
		deferredResult.addMethod(this.user(), 'getRecord', someData['cardReference']);
		deferredResult.addMethodcaller('directLogins');
		deferredResult.addCallback(MochiKit.Base.itemgetter(someData['directLoginReference']));
//		deferredResult.addMethodcaller('runDirectLogin');
		deferredResult.addCallback(Clipperz.PM.UI.Common.Controllers.DirectLoginRunner.openDirectLogin);
		deferredResult.callback();

		return deferredResult;
	},

	//=========================================================================

	'addMetaTag': function (aName, aContent) {
		var	metaTag;

		metaTag = document.createElement('meta');
		metaTag.name = aName;
		metaTag.content = aContent;
		document.getElementsByTagName('head')[0].appendChild(metaTag);
	},

	'addLinkTag': function (aRel, anHref) {
		var linkTag;

		linkTag = document.createElement('link');
		linkTag.rel = aRel;
		linkTag.href = anHref;
		document.getElementsByTagName('head')[0].appendChild(linkTag);
	},

	//=========================================================================
	__syntaxFix__: "syntax fix"
});