/*
 * Created by SharpDevelop.
 * User: turugina
 * Date: 2009/06/15
 * Time: 23:05
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;
using System.Xml.XPath;
using System.IO;

namespace TwitterBlock
{
	/// <summary>
	/// Description of Twitter.
	/// </summary>
	public class Twitter
	{

		private AccountInfo account;
		public Twitter(AccountInfo account)
		{
			this.account = account;
		}

		public IList<UserInfo> GetFollowers()
		{
			XPathDocument doc = this.Request("statuses/followers", WebRequestMethods.Http.Get);
			XPathNavigator nav = doc.CreateNavigator();
			XPathNodeIterator it = nav.Select("//user");
			IList<UserInfo> followers = new List<UserInfo>();
			foreach (XPathNavigator nav_ in it )
			{
				followers.Add(UserInfoHelper.Parse(nav_));
			}
			return followers;
		}
		
		public void BlockUser(string userId)
		{
			this.Request("blocks/create/"+userId, WebRequestMethods.Http.Post);
		}
		
		private XPathDocument Request(string pathPart, string method)
		{
			Uri uri = new Uri ("http://twitter.com/"+pathPart+".xml");
			
			HttpWebRequest req = HttpWebRequest.Create(uri) as HttpWebRequest;
			req.Credentials = new NetworkCredential(account.UserName, account.Password);
			req.Method = method;
			
			HttpWebResponse res = req.GetResponse() as HttpWebResponse;
			if (res.StatusCode != HttpStatusCode.OK)
			{
				throw new Exception(res.StatusDescription);
			}
			
			return new XPathDocument(res.GetResponseStream());			
		}
		
	}
}
