App.Models.Envelope = Backbone.Model.extend({
	to: [],
	cc: [],
	bcc:[],

	defaults : {
		/*
		isNew:false,
		account:null,
		to:[],
		cc:[],
		bcc:[],
		subject:'Untitled Message',
		body:'',
		attachments:[]
		*/
		Account:0,
		emailTo:'',
		emailCc:'',
		emailBcc:'',
		emailSubject:'Untitled Message',
		emailBodyHtml:'',
		attachments:{},
		readReceiptRequested:'false',
		isDraft: false,
		relatedDraftUID: null
	},

});

App.Models.Envelope.prototype.validateDraft = function(){
	var subject, body, attchments;

	subject = this.get('emailSubject');
	body = this.get('body') || this.get('emailBodyHtml');
	attachments = this.get('attachments');

	if(this._joinAddresses('to').length){
		return true;
	}

	if(this._joinAddresses('cc').length){
		return true;
	}

	if(this._joinAddresses('bcc').length){
		return true;
	}

	if(subject && subject.length && subject !== this.defaults.emailSubject){
		return true;
	}

	if(body && body.length){
		return true;
	}

	if(! _.isEmpty(attachments) ){
		return true;
	}

	return false;
}

App.Models.Envelope.prototype.readReceipt = function(){
	var receipt;

	receipt = (this.get('readReceiptRequested')==='true')? true : false;
	return receipt;
}

App.Models.Envelope.prototype.toggleReadReceipt = function(){
	var receipt = this.get('readReceiptRequested');
	if(receipt === 'true'){
		this.set('readReceiptRequested','false');
	} else {
		this.set('readReceiptRequested','true');
	}
}

App.Models.Envelope.prototype.prepare = function(){
	
	this.set( 'emailTo', this._joinAddresses('to') );
	this.set( 'emailCc', this._joinAddresses('cc') );
	this.set( 'emailBcc', this._joinAddresses('bcc') );
	
	/*
	_.each(this['attachments'],function(atch,i){
		var name = atch.filenameOriginal.replace(/\./,'');

		_.each(_.keys(atch),function(key,i){
			this['attachments'][name][key] = atch[key];
		});
	});
	*/

	return this;
}

App.Models.Envelope.prototype._joinAddresses = function(fieldName){
	var first, string;

	first  = true;
	string = '';

	try{

		if(typeof this[fieldName] === 'undefined'){
			throw new Error('Envelope._joinAddresses: '+fieldName+' does not exist');
		}

		_.each(this[fieldName],function(recipient,i){
			if(recipient.validate()){
				var comma = first? '' : ',';
				string += comma + recipient.getFullFormatedAddress();
				first = false;
			}
		});

	} catch (e) {
		console.log(e);
	}

	return string;
},

App.Models.Envelope.prototype._push = function(fieldName,value){
	// var field = _.clone( this.get(fieldName) );
	var field = _.clone( this[fieldName] );

	try{

		if(typeof field === 'undefined'){
			throw new Error('Envelope._push: '+fieldName+' does not exist');
		}

		field.push(value);
		this[fieldName] = field;
	} catch(e) {
		console.log(e);
	}
	
};

App.Models.Envelope.prototype.setAttachment = function(attachment){
	var key,atc;

	key = attachment.filenameOriginal.replace(/\W/g,'').concat(Date.now());
	obj = 
	atc = _.clone( this.get('attachments') );

	atc[key] = {};

	atc[key]['filenameFS'] = attachment.filenamefs;
	atc[key]['filenameOriginal'] = attachment.filenameOriginal;
	atc[key]['mimeType'] = attachment.mimeType;

	this.set('attachments',atc);

};

App.Models.Envelope.prototype.setRecipient = function(fieldName,recipient){
	this._push(fieldName,recipient);
};

App.Models.Envelope.prototype.removeAddress = function(cid){
	var fields;

	fields = ['to','cc','bcc'];

	OUT_OF_LOOP:
	for(var i=0; i<fields.length;i++){
		list = this[fields[i]];
		for(var x=0; x<list.length;x++){
			if(list[x].cid===cid){
				list.splice(x,1);
				break OUT_OF_LOOP;
			}
		}
	}
};
/*

App.Models.Envelope.prototype.setToRecipient = function(recipient){
	this.setRecipient('to',recipient);
};

App.Models.Envelope.prototype.setCcRecipient = function(recipient){
	this.setRecipient('cc',recipient);
};

App.Models.Envelope.prototype.setBccRecipient = function(recipient){
	this.setRecipient('bcc',recipient);
};
*/
