/*
 * PrintDrop
 * Copyright (c) 2008, Blue Static <http://www.bluestatic.org>
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU 
 * General Public License as published by the Free Software Foundation; either version 2 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not, 
 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#import "AppController.h"
#import <libssh2.h>
#import <sys/socket.h>
#import <arpa/inet.h>
#include <netdb.h>

@interface AppController (Private)

//- (BOOL)uploadFile;
- (void)setStatus:(NSString *)msg isError:(BOOL)error;

@end


@implementation AppController

/**
 * Set up the printer list
 */
- (id)init
{
	if (self = [super init])
	{
		printers = [NSMutableArray array];
		
		NSArray *values = [NSArray arrayWithObjects:@"Double-Sided, Stapled $0.05", @"publp", nil];
		NSArray *keys = [NSArray arrayWithObjects:@"displayName", @"unixName", nil];
		[printers addObject:[NSDictionary dictionaryWithObjects:values forKeys:keys]];
		
		values = [NSArray arrayWithObjects:@"Single-Sided, Stapled $0.10", @"pubps", nil];
		[printers addObject:[NSDictionary dictionaryWithObjects:values forKeys:keys]];
		
		values = [NSArray arrayWithObjects:@"Double-Sided, Not Stapled $0.05", @"publpns", nil];
		[printers addObject:[NSDictionary dictionaryWithObjects:values forKeys:keys]];
		
		values = [NSArray arrayWithObjects:@"Single-Sided, Not Stapled $0.10", @"pubpsns", nil];
		[printers addObject:[NSDictionary dictionaryWithObjects:values forKeys:keys]];
	}
	return self;
}

/**
 * Sets the status text
 */
- (void)setStatus:(NSString *)msg isError:(BOOL)error
{
	[status setStringValue:msg];
	if (error)
	{
		[status setTextColor:[NSColor redColor]];
		[progress stopAnimation:self];
	}
	else
	{
		[status setTextColor:[NSColor blackColor]];
	}
}

/**
 * Sends an item to the printer
 */
- (IBAction)print:(id)sender
{
	[progress startAnimation:self];
	[progress setHidden:NO];
	[status setHidden:NO];
	
	NSString *printer = [[printersController selection] valueForKey:@"unixName"];
	FILE *localFile;
	struct stat fileInfo;
	
	[self setStatus:@"Connecting to acs.bu.edu" isError:NO];
	struct sockaddr_in sin;
	int sock = socket(AF_INET, SOCK_STREAM, 0);
	sin.sin_port = htons(22);
	sin.sin_family = AF_INET;
	
	struct hostent *host = gethostbyname("acs.bu.edu");
	memcpy(&sin.sin_addr, host->h_addr_list[0], host->h_length);
	
	if (connect(sock, (struct sockaddr *)(&sin), sizeof(struct sockaddr_in)) != 0)
	{
		return [self setStatus:@"Could not connect to acs.bu.edu" isError:YES];
	}
	
	LIBSSH2_SESSION *ssh = libssh2_session_init();
	if (ssh == NULL)
	{
		return [self setStatus:@"Failed to initialize SSH context" isError:YES];
	}
	
	if (libssh2_session_startup(ssh, sock))
	{
		return [self setStatus:@"Could not tunnel over SSH" isError:YES];
	}
	
	if (libssh2_userauth_password(ssh, [[username stringValue] UTF8String], [[password stringValue] UTF8String]))
	{
		[self setStatus:@"Bad username/password" isError:YES];
		goto shutdown;
	}
	
	stat([[dragRegion filePath] UTF8String], &fileInfo);
	
	LIBSSH2_CHANNEL *channel = libssh2_scp_send(ssh, "~/tempupload.pdf", 0755, (unsigned long)fileInfo.st_size);
	if (!channel)
	{
		[self setStatus:@"Unable to open upload SCP session" isError:YES];
		goto shutdown;
	}
	
	[self setStatus:@"Uploading file..." isError:NO];
	
	localFile = fopen([[dragRegion filePath] UTF8String], "r");
	char buf[1024];
	char *pbuf;
	int numread, numwrote;
	do
	{
		numread = fread(buf, 1, sizeof(buf), localFile);
		if (numread <= 0)
		{
			break;
		}
		
		pbuf = buf;
		do
		{
			numwrote = libssh2_channel_write(channel, pbuf, numread);
			pbuf += numwrote;
			numread -= numread;
		} while (numwrote > 0);
		
	} while(1);
	
	[self setStatus:@"File uploaded!" isError:NO];
	
	libssh2_channel_send_eof(channel);
	libssh2_channel_wait_eof(channel);
	libssh2_channel_wait_closed(channel);
	libssh2_channel_free(channel);
	channel = NULL;
	
shutdown:
	libssh2_session_disconnect(ssh, "Normal disconnect.");
	libssh2_session_free(ssh);
	
	close(sock);
	
	[progress stopAnimation:self];
}

@end
