/*
	$Id: Account.cs 22 2010-01-15 22:30:39Z catwalk $
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Hiyoko.Net.OAuth;

namespace Hiyoko.Net.Twitter{
	public class Account{
		public AccessToken AccessToken{get; set;}
		public User User{get; private set;}
		
		public Account(){
		}
		
		public Account(AccessToken accessToken){
			this.AccessToken = accessToken;
		}
		
		public void VerifyCredential(){
			string xmlString;
			using(HttpWebResponse res = (HttpWebResponse)TwitterAPI.VerifyCredential(this.AccessToken).WebRequest.GetResponse())
			using(Stream stream = res.GetResponseStream())
			using(StreamReader reader = new StreamReader(stream, Encoding.UTF8)){
				xmlString = reader.ReadToEnd();
			}
			this.User = User.FromXElement(XElement.Parse(xmlString));
		}
		
		public bool IsVerified{
			get{
				return (this.User.Id != 0);
			}
		}
		
		public Collection<Status> GetHomeTimeline(int count, int page, long sinceId, long maxId){
			XElement xml;
			return this.GetHomeTimeline(count, page, sinceId, maxId, out xml);
		}
		
		public Collection<Status> GetHomeTimeline(int count, int page, long sinceId, long maxId, out XElement xml){
			Collection<Status> timeline = new Collection<Status>();
			string xmlString;
			using(HttpWebResponse res = (HttpWebResponse)TwitterAPI.GetHomeTimeline(this.AccessToken, count, page, sinceId, maxId).WebRequest.GetResponse())
			using(Stream stream = res.GetResponseStream())
			using(StreamReader reader = new StreamReader(stream, Encoding.UTF8)){
				xmlString = reader.ReadToEnd();
			}
			xml = XElement.Parse(xmlString);
			foreach(XElement status in xml.Elements("status")){
				timeline.Add(Status.FromXElement(status));
			}
			
			return timeline;
		}
		
		public void UpdateStatus(string status, long replyTo, string source){
			WebRequestData data = TwitterAPI.UpdateStatus(this.AccessToken, status, replyTo, source);
			data.WriteRequestData();
		}
		
		public void DestroyStatus(long id){
			WebRequestData data = TwitterAPI.DestroyStatus(this.AccessToken, id);
			data.WriteRequestData();
		}
		
		public void CreateFavorite(long id){
			WebRequestData data = TwitterAPI.CreateFavorite(this.AccessToken, id);
			data.WriteRequestData();
		}
		
		public void CreateBlock(long id){
			WebRequestData data = TwitterAPI.CreateBlock(this.AccessToken, id);
			data.WriteRequestData();
		}
		
		public void DestroyFriendship(long id){
			WebRequestData data = TwitterAPI.DestroyFriendship(this.AccessToken, id);
			data.WriteRequestData();
		}
	}
}