function encodeURI(q){
	return Ti.Network.encodeURIComponent(q);
}

exports.Twit = (function(){
	var ter = function(){
		this.consumerKey = null;
		this.consumerSecret = null;
		this.bearerKey = null;
		this.tokenKey = null;
		this.endpoint_base = "https://api.twitter.com/";
		this.endpoint = this.endpoint_base + "1.1/";
		this.authorized = false;
		this.xhr = Ti.Network.createHTTPClient();
		this.xhrCancel = false;
	};
	
	ter.prototype.setConsumerKey = function(key, secret){
		this.consumerKey = key;
		this.consumerSecret = secret;
		this.bearerKey = "" + Ti.Utils.base64encode(encodeURI(this.consumerKey) + ":" + encodeURI(this.consumerSecret));
		this.bearerKey = this.bearerKey.replace(/[\r\n]+/, "");
		this.tokenKey = Ti.App.Properties.getString("twitterTokenKey", "");
		if(this.tokenKey){
			this.authorized = true;
		}
	};
	
	ter.prototype.login = function(callback){
		var self = this,
			url = self.endpoint_base + "oauth2/token",
			field = "grant_type=client_credentials";
			
		if(!self.authorized){
			self.xhr.open("POST", url, true);
			self.xhr.setRequestHeader("Authorization", "Basic " + self.bearerKey);
			self.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			self.xhr.setRequestHeader('User-Agent', Titanium.userAgent);
			self.xhr.setTimeout = 5000;
			
			self.xhr.onload = function(){
				var responseData = JSON.parse(this.responseText);
				Ti.App.Properties.setString("twitterTokenKey", responseData.access_token);
				self.tokenKey = responseData.access_token;
				self.authorized = true;
				callback.apply();
			};
			self.xhr.onerror = function(e){
				var status_code = OS_IOS ? e.code : e.status;
				var responseText = JSON.parse(this.responseText);
				alert("status:" + status_code +"\n"
					+ " code:" + responseText.errors[0].code + "\n"
					+ "message:" + responseText.errors[0].message);
			};
			self.xhr.send(field);
		}
	};
	
	ter.prototype.logout = function(){
		var self = this,
			url = self.endpoint_base + "oauth2/invalidate_token",
			field = "access_token=" + self.tokenKey;
		self.xhr.open("POST", url, true);
		self.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		self.xhr.setRequestHeader("Authorization", "Basic " + self.bearerKey);
		self.xhr.setRequestHeader('User-Agent', Ti.userAgent);
		self.xhr.setTimeout = 5000;

		self.xhr.onload = function(){
			var responseData = JSON.parse(this.responseText);
			Ti.App.Properties.setString("twitterTokenKey", "");
			Ti.API.error("logout");
		};
		self.xhr.error = function(e){
			Ti.API.error("logout error" + e.error);
		};
		self.xhr.send(field);
	};
	
	ter.prototype.request = function(path, callback){
		var self = this,
			url = self.endpoint + path;
		
		if(self.authorized){
			self.xhr.open("GET", url, true);
			self.xhr.setRequestHeader("Authorization", "Bearer " + self.tokenKey);
			self.xhr.setRequestHeader("User-Agent", Ti.userAgent);
			self.xhr.setTimeout = 5000;
			
			self.xhr.onload = function(e){
				if(this.responseText != null || self.xhrCancel != true){
					var data = JSON.parse(this.responseText);
					if(data.errors){
						callback({
							status: self.xhr.status,
							success: false,
							limit_reset: self.xhr.getResponseHeader("x-rate-limit-reset")
						}, data);
					}else{
						callback({
							status: self.xhr.status,
							success: true,
							limit_reset: self.xhr.getResponseHeader("x-rate-limit-reset")
						}, data);
					}
				}else{
					self.xhrCancel = false;
				}
			};
			self.xhr.error = function(e){
				callback({
					status: self.xhr.status,
					success: false,
					limit_reset: self.xhr.getResponseHeader("x-rate-limit-reset")
				}, e);
			};
			self.xhr.onreadystatechange = function(e){
//alert(self.xhr.getAllResponseHeaders());
//Ti.API.error("limit: " + self.xhr.getResponseHeader("x-rate-limit-remaining") + "/" +self.xhr.getResponseHeader("x-rate-limit-limit"));
//Ti.API.error("limit reset: " + self.xhr.getResponseHeader("x-rate-limit-reset"));
				if(OS_ANDROID && self.xhr.status == 429){
					callback({
						status: self.xhr.status,
						success: false,
						limit_reset: self.xhr.getResponseHeader("x-rate-limit-reset")
					}, {"errors":[{"message":"Rate limit exceeded","code":88}]});
				}
			};
			self.xhr.send();
		}
	};
	
	ter.prototype.authorize = function(){
		return this.authorized;
	};
	
	ter.prototype.httpCancel = function(){
		this.xhrCancel = true;
		this.xhr.abort();
		if(Ti.Platform.osname != "android"){
			this.xhrCancel = false;
		}
	};
	
	ter.prototype.httpClose = function(){
		this.xhr.onload = null;
		this.xhr.onreadystatechange = null;
		this.xhr.ondatastream = null;
		this.xhr.onsendstream = null;
		this.xhr.onerror = null;
		this.xhr = null;
	};
	
	ter.prototype.getHttpReadyState = function(){
		return this.xhr.readyState;
	};
	
	ter.prototype.getStatus = function(){
		return this.xhr.status;
	};
	
	return ter;
})(this);