#import <ObjFW/ObjFW.h>
#import <ObjXMPP/ObjXMPP.h>

#import "PEPThread.h"

#define NS_PUBSUB @"http://jabber.org/protocol/pubsub"
#define NS_TUNE @"http://jabber.org/protocol/tune"

@implementation PEPThread: OFThread
- (OFMutableDictionary*)MPD_responeFromSocket: (OFTCPSocket*)sock
{
	OFString *answer;
	OFMutableDictionary *response = [OFMutableDictionary dictionary];
	while ((answer = [sock readLine]) && ![answer hasPrefix: @"OK"]) {
		size_t index;
		index = [answer indexOfFirstOccurrenceOfString: @":"];
		if (index == OF_INVALID_INDEX)
			continue;
		[response setObject: [answer substringFromIndex: index + 2
							toIndex: answer.length]
			     forKey: [answer substringFromIndex: 0
							toIndex: index]];
	}

	return response;
}

- (id)main
{
	OFTCPSocket *sock = [OFTCPSocket socket];
	[sock connectToHost: @"localhost"
		       port: 6600];
	[self MPD_responeFromSocket: sock];
	while (1) {
		OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
		OFMutableDictionary *response;
		OFString *answer;
		XMPPIQ *tuneIQ = [XMPPIQ IQWithType: @"set"
						 ID: [object generateStanzaID]];
		OFXMLElement *pubsub = [OFXMLElement
		    elementWithName: @"pubsub"
			  namespace: NS_PUBSUB];
		[tuneIQ addChild: pubsub];
		OFXMLElement *publish = [OFXMLElement 
		    elementWithName: @"publish"
			  namespace: NS_PUBSUB];
		[publish addAttributeWithName: @"node"
				  stringValue: NS_TUNE];
		[pubsub addChild: publish];
		OFXMLElement *item = [OFXMLElement elementWithName: @"item"
							 namespace: NS_PUBSUB];
		[publish addChild: item];
		OFXMLElement *tune = [OFXMLElement elementWithName: @"tune"
							 namespace: NS_TUNE];
		[item addChild: tune];
		[sock writeLine: @"status"];
		response = [self MPD_responeFromSocket: sock];
		if ([[response objectForKey: @"state"] isEqual: @"play"]) {
			[sock writeLine: @"currentsong"];
			response = [self MPD_responeFromSocket: sock];
			if ((answer = [response objectForKey: @"Artist"]))
				[tune addChild: [OFXMLElement
				    elementWithName: @"artist"
					  namespace: NS_TUNE
					stringValue: answer]];
			if ((answer = [response objectForKey: @"Time"]))
				[tune addChild: [OFXMLElement
				    elementWithName: @"length"
					  namespace: NS_TUNE
					stringValue: answer]];
			if ((answer = [response objectForKey: @"Album"]))
				[tune addChild: [OFXMLElement
				    elementWithName: @"source"
					  namespace: NS_TUNE
					stringValue: answer]];
			if ((answer = [response objectForKey: @"Title"]))
				[tune addChild: [OFXMLElement
				    elementWithName: @"title"
					  namespace: NS_TUNE
					stringValue: answer]];
			if ((answer = [response objectForKey: @"Track"]))
				[tune addChild: [OFXMLElement
				    elementWithName: @"track"
					  namespace: NS_TUNE
					stringValue: answer]];
		}
		[object sendStanza: tuneIQ];
		[sock writeLine: @"idle player"];
		[self MPD_responeFromSocket: sock];
		[pool release];
	}

	return nil;
}
@end
