/*************************************************************************
* Rutoken                                                                *
* Copyright (c) 2003-2017, CJSC Aktiv-Soft. All rights reserved.         *
* Подробная информация:  http://www.rutoken.ru                           *
*************************************************************************/

#import "ViewController.h"
#import "Pkcs11.h"
#import "CryptoPro.h"

// Определить внешний символ, используемый CPROCSP.framework
extern bool USE_CACHE_DIR;
bool USE_CACHE_DIR = false;

NSString* kSmInitAlertTitle=@"SM Activation";


@interface ViewController ()
- (void)setTxtValue:(NSString*) data;
- (void)addTxtValue:(NSString*) data;
@end

@implementation ViewController
- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
	if([readers count] > 0)
		return [readers count];
	else
		return 1;
}

- (UIView *)pickerView:(UIPickerView *)pickerView
		viewForRow: (NSInteger)row
		forComponent: (NSInteger)component
		reusingView: (UIView *)view
{
	NSString* title=nil;
	if([readers count] > 0)
	{
		CPReader* reader = [readers objectAtIndex:row];
		ReaderStatus status = [reader getReaderStatus];
		NSString* statusString = nil;
		switch(status) {
			case kValidReader:
				statusString = @"( RDY )";
				break;
			case kNoMediaReader:
				statusString = @"( !SM )";
				break;
			case kErrorReader:
				statusString = @"( ERR )";
				break;
		}
		title=[NSString stringWithFormat:@"%@   %@", statusString, [reader name]];
	}
	else
		title=@"No readers. Press \"List readers\" to update";
	
	UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
	label.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:12];
	label.text = [NSString stringWithFormat:@"    %@", title];
	return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component
{
	currentReader = nil;
	if(row < [readers count]) {
		CPReader* reader = [readers objectAtIndex:row];
		currentReader=reader;
	}
}

- (void)viewDidLoad
{
	[super viewDidLoad];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logData:)
	                                             name:@"LogData" object:nil];
	readers = [[NSArray alloc] init];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
		return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
	} else {
		return YES;
	}
}

- (IBAction)ListReaders:(id)sender {
	[self doListReaders];
	[picker reloadAllComponents];
	[self pickerView: picker didSelectRow:[picker selectedRowInComponent:0] inComponent:0];
}

- (IBAction)StartSM:(id)sender {
	if(![currentReader isRutoken]) {
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:kSmInitAlertTitle message:@"Error! This is not rutoken!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		alert.alertViewStyle = UIAlertViewStyleDefault;
		[alert show];
	} else if([currentReader getReaderStatus] == kValidReader) {
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:kSmInitAlertTitle message:@"Error! This rutoken does not need initializing SM channel" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		alert.alertViewStyle = UIAlertViewStyleDefault;
		[alert show];
	} else {
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:kSmInitAlertTitle message:@"Please, be kind to provide SM activation password" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		alert.alertViewStyle = UIAlertViewStylePlainTextInput;
		[alert show];
	}
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	if([[alertView title] rangeOfString:kSmInitAlertTitle].location != NSNotFound ){
		[self doStartSmOnReader:currentReader withPassword:[[alertView textFieldAtIndex:0] text]];
	}
}

- (IBAction)CreateContainer:(id)sender {
	if([currentReader getReaderStatus] != kValidReader) {
		UIAlertView * alert = [[UIAlertView alloc]
							   initWithTitle:@"Create container"
							   message:@"Error! This reader seems to be not valid yet!"
							   delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		alert.alertViewStyle = UIAlertViewStyleDefault;
		[alert show];
	} else {
		CFUUIDRef uuid = CFUUIDCreate(NULL);
		CFStringRef str = CFUUIDCreateString(NULL, uuid);
		NSString* containerName = [NSString stringWithString:(__bridge NSString*)str];
		CFRelease(uuid);
		
		[self doCreateContainer:containerName onReader:currentReader];
	}
}

- (IBAction)ListContainers:(id)sender {
	[self doListContainers];
}

- (void)doListReaders {
	[self setTxtValue:@"Enumerate readers\n"];
	readers = [CryptoPro getReaderList];
}

- (void)doStartSmOnReader: (CPReader*)reader withPassword: (NSString*)password  {
	[self setTxtValue:@"Init SM channel\n"];
	[PKCS11 setActivationPassword: password forReader:[reader name]];
	[self addTxtValue:@"Press \"List readers\" to update device status\n"];
}

- (void)doListContainers {
	[self setTxtValue:@"Enumerate containers\n"];
	id containers = [CryptoPro getContainerList];
	if([containers count] > 0) {
		[self addTxtValue:@"Containers availible:\n"];
		for (NSString* container in containers)
			[self addTxtValue:[NSString stringWithFormat:@"%@\n", container]];
	}
}

- (void)doCreateContainer: (NSString*)containerName onReader: (CPReader*)reader {
	[self setTxtValue:[NSString stringWithFormat:@"Creating container %@\n", containerName]];
	[CryptoPro createNewKeyset:containerName forReader:reader];
}

- (void)setTxtValue:(NSString*) data
{
	logTextView.text = data;
	[logTextView flashScrollIndicators];
	NSRange range = NSMakeRange(logTextView.text.length - 1, 1);
	[logTextView scrollRangeToVisible:range];
}

- (void)addTxtValue:(NSString*) data
{
	NSString *textValue = [NSString stringWithFormat:@"%@%@", logTextView.text, data];
	[self setTxtValue:textValue];
}

- (void)logData:(NSNotification*)notification {
	NSDictionary* userInfo = [notification userInfo];
	NSString* data = [userInfo objectForKey:@"data"];
	[self addTxtValue:data];
}
@end
