define([
	'../../internals'
], function( internals ){

	//faster than str += " "
	var StringBuffer = function(){
		this.buffer = [];
	};
	StringBuffer.prototype.append = function(string){
		this.buffer.push(string);
		return this;
	};
	StringBuffer.prototype.toString = function(){
		return this.buffer.join("");
	};
	
	var OBJWriter = function(){
		this.VERSION = "0.3";
		this.__stringBuffer = new StringBuffer();
		this.objStream = undefined;
		this.__filename = "objwriter.obj";
		this._numVerticesWritten = 0;
		this._numNormalsWritten = 0;
	};


	OBJWriter.prototype = {
		/**
		 * begin saving
		 * @param {WritableStream | String} [stream] stream can be a node.js WritableStream, or it can be a filename or undefined
		 */
		beginSave: function( stream ){
			if( typeof stream == 'string' ){
				//if node.js create a writeable stream with this filename
			} else if( internals.hasProperties(stream,['write','end','writable'] && stream.writable)){
				this.objStream = stream;
			} else {
			}
			this._handleBeginSave();
		},

		endSave: function(){
			if(this.objStream !== undefined ){
				try {
					this.objStream.destroy();
				} catch( e ){

				}
			}
		},

		face: function( a, b, c ){
			this.__stringBuffer.append("f " + a + " " + b + " " + c + "\n");
		},

		faceList: function(){
			this.__stringBuffer.append("s off \n");
		},

		faceWithNormals: function( a, b, c, na, nb, nc ){
			this.__stringBuffer.append("f " + a + "//" + na + " " + b + "//" + nb + " " + c + "//" + nc + "\n");
		},

		getCurrNormalOffset: function(){
			return this._numNormalsWritten;
		},

		getCurrVertexOffset: function(){
			return this._numVerticesWritten;
		},

		//not in java version
		getOutput: function(){
			return this.__stringBuffer.toString();
		},

		_handleBeginSave: function(){
			this.numVerticesWritten = 0;
			this.numNormalsWrittern = 0;
			this.__stringBuffer.append("# generated by OBJExport (js) v" + this.VERSION+'\n');
		},

		newObject: function( name ){
			this.__stringBuffer.append("o " + name + "\n");
		},

		normal: function( vecN ){
			this.__stringBuffer.append("vn " + vecN.x + " " + vecN.y + " " + vecN.z + "\n");
			this._numNormalsWritten++;
		},

		vertex: function( vecV ){
			this.__stringBuffer.append("v " + vecV.x + " " + vecV.y + " " + vecV.z +"\n");
			this._numVerticesWritten++;
		}
	};


	return OBJWriter;

});