// Copyright 2001-2003, Danger, Inc.  All Rights Reserved.
// This file is subject to the Danger, Inc. Sample Code License,
// which is provided in the file SAMPLE_CODE_LICENSE.
// Copies are also available from http://developer.danger.com/

package com.danger.livejournal;

import danger.util.StringUtils;
import danger.net.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;

public class Network
{
	//*	--------------------	Post

	public static void
	Post(JournalDataRecord j)
	{
	StringBuffer	params = new StringBuffer();
	String			headers = GetHeaders();

		PrepParamData(params, "postevent");
		AddParam(params, "event", j.Entry());

		AddBaseEntryItems(j, params);
		AddDate(j, params);
		AddProperties(j, params);
				
		HTTPConnection.post(kStr_Server, headers, params.toString(), (short) 0, 0);
	}

	//*	--------------------	Edit

	public static void
	Edit(JournalDataRecord j, boolean inDelete)
	{
	StringBuffer	params = new StringBuffer();
	String			headers = GetHeaders();
	
		PrepParamData(params, "editevent");
		AddParam(params, "itemid", "" + j.ItemID());

		if (inDelete)
			AddParam(params, "event", "");
		else
			AddParam(params, "event", j.Entry());
			
		AddBaseEntryItems(j, params);
		//*	Note, no date modifications allowed (for now)
		AddProperties(j, params);

		HTTPConnection.post(kStr_Server, headers, params.toString(), (short) 0, 0);
	}

	//*	--------------------	AddBaseEntryItems

	private static final void
	AddBaseEntryItems(JournalDataRecord j, StringBuffer params)
	{
		//*	hiptop native line ending is \r
		AddParam(params, "lineendings", "mac");
		
		AddParam(params, "subject", j.Subject());

		if (0 == j.Security())
			AddParam(params, "security", "public");
		else
			AddParam(params, "security", "private");

		if (! StringUtils.isEmpty(j.Journal()))
			AddParam(params, "usejournal", j.Journal());
	}
	
	//*	--------------------	AddDate

	private static final void
	AddDate(JournalDataRecord j, StringBuffer params)
	{
	Calendar	date = Calendar.getInstance();

		date.setTimeInMillis(((long) j.Date()) * 1000L);

		AddParam(params, "year", "" + date.get(Calendar.YEAR));
		
		//*	Java's months are 0-based, LiveJournal's are 1-based
		AddParam(params, "mon", "" + (date.get(Calendar.MONTH) + 1));
		AddParam(params, "day", "" + date.get(Calendar.DATE));
		AddParam(params, "hour", "" + date.get(Calendar.HOUR));
		AddParam(params, "min", "" + date.get(Calendar.MINUTE));
	}

	//*	--------------------	AddProperties

	private static final void
	AddProperties(JournalDataRecord j, StringBuffer params)
	{
		//*	Note the explicit reversal of the logic for this property
		if (j.AllowComments())
			AddParam(params, "prop_opt_nocomments", "0");
		else
			AddParam(params, "prop_opt_nocomments", "1");
			
		//*	Note the explicit reversal of the logic for this property
		if (j.AllowEmail())
			AddParam(params, "prop_opt_noemail", "0");
		else
			AddParam(params, "prop_opt_noemail", "1");
			
		AddParam(params, "prop_current_mood", j.Mood());
		AddParam(params, "prop_current_music", j.Music());
		AddParam(params, "prop_picture_keyword", j.Pic());
	}

	//*	--------------------	Login

	public static void
	Login()
	{
	StringBuffer	params = new StringBuffer();

		PrepParamData(params, "login");
		
		//*	Report our client version
		AddParam(params, "clientversion", "Danger-hiptop/0.5.1");
		
		//*	Request picture keywords
		AddParam(params, "getpickws", "1");

		//*	< WIP - cjd >
		//*	We have no way to guarantee that we could display a given picture if we loaded
		//*	it.  So, until support for that gets sorted, leave this commented out.
		//*	AddParam(params, "getpickwurls", "1");

		HTTPConnection.post(kStr_Server, null, params.toString(), (short) 0, 0);
	}

	//*	--------------------	GetFriends

	public static void
	GetFriends()
	{
	StringBuffer	params = new StringBuffer();
	String			headers = GetHeaders();

		PrepParamData(params, "getfriends");

		HTTPConnection.post(kStr_Server, headers, params.toString(), (short) 0, 0);
	}

	//*	--------------------	AddFriend

	public static void
	AddFriend(String inFriendName)
	{
	StringBuffer	params = new StringBuffer();
	String			headers = GetHeaders();
	
		PrepParamData(params, "editfriends");
		AddParam(params, "editfriend_add_1_user", inFriendName);

		HTTPConnection.post(kStr_Server, headers, params.toString(), (short) 0, 0);
	}

	//*	--------------------	DeleteFriend

	public static void
	DeleteFriend(String inFriendName)
	{
	StringBuffer	params = new StringBuffer();
	String			headers = GetHeaders();

		PrepParamData(params, "editfriends");
		AddParam(params, "editfriend_delete_" + inFriendName, "" + 1);

		HTTPConnection.post(kStr_Server, headers, params.toString(), (short) 0, 0);
	}

	//*	--------------------	Sync

	public static void
	Sync(String inLastDate)
	{
	StringBuffer	params = new StringBuffer();
	String			headers = GetHeaders();

		PrepParamData(params, "syncitems");

		if (! StringUtils.isEmpty(inLastDate))
			AddParam(params, "lastsync", inLastDate);

		HTTPConnection.post(kStr_Server, headers, params.toString(), (short) 0, 0);
	}

	//*	--------------------	SyncItem

	public static void
	SyncItem(int inItemNum)
	{
	StringBuffer	params = new StringBuffer();
	String			headers = GetHeaders();

		PrepParamData(params, "getevents");
		AddParam(params, "prefersubject", "0");
		AddParam(params, "selecttype", "one");
		AddParam(params, "itemid", "" + inItemNum);
		AddParam(params, "lineendings", "mac");

		HTTPConnection.post(kStr_Server, headers, params.toString(), (short) 0, 0);
	}

	//*	--------------------	GetSyncDelta

	public static void
	GetSyncDelta(String inLastDate)
	{
	StringBuffer	params = new StringBuffer();
	String			headers = GetHeaders();

		PrepParamData(params, "getevents");
		AddParam(params, "prefersubject", "0");
		AddParam(params, "selecttype", "syncitems");
		AddParam(params, "lastsync", inLastDate);
		AddParam(params, "lineendings", "mac");

		HTTPConnection.post(kStr_Server, headers, params.toString(), (short) 0, 0);
	}

	//*	--------------------	CheckFriends

	public static void
	CheckFriends(String inLastTime)
	{
	StringBuffer	params = new StringBuffer();
	String			headers = GetHeaders();

		PrepParamData(params, "checkfriends");

		if (! StringUtils.isEmpty(inLastTime))
			AddParam(params, "lastupdate", inLastTime);

		HTTPConnection.post(kStr_Server, headers, params.toString(), (short) 0, 0);
	}

	//*	--------------------	PrepParamData

	private static void
	PrepParamData(StringBuffer params, String mode)
	{
		AddParam(params, "mode", mode);
		AddParam(params, "user", LiveJournal.Instance().Username());
		AddParam(params, "password", LiveJournal.Instance().Password());
		AddParam(params, "ver", "1");
	}

	//*	--------------------	AddParam

	private static void
	AddParam(StringBuffer params, String argument, String value)
	{
		if (params.length() > 0)
			params.append('&');
			
		params.append(argument);
		params.append('=');
		try {
			params.append(URLEncoder.encode(value, "UTF-8"));
		}
		catch (UnsupportedEncodingException e) { }
	}

	//*	--------------------	GetHeaders

	private static final String
	GetHeaders()
	{
	String	s = null;
	
		if (true == LiveJournal.FastServerEnabled())
			s = "Cookie: ljfastserver=1";
			
		return s;
	}

	//*	--------------------------------	Constants

	private static final String	kStr_Server		=	"http://www.livejournal.com/interface/flat";
}
