//
//  ICFViewController.m
//  Keychain
//
//  Created by Kyle Richter on 4/28/13.
//  Copyright (c) 2013 Kyle Richter. All rights reserved.
//

#import "ICFViewController.h"

#define kEnterExistingPinAlert 1
#define kEnterNewPinAlert 2


@interface ICFViewController ()

@end

@implementation ICFViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    pinWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"com.ICF.keychain.pin" accessGroup:nil];
    [pinWrapper setObject:(__bridge id)(kSecAttrAccessibleWhenUnlocked) forKey: (__bridge id)kSecAttrAccessible];
    [pinWrapper setObject:@"pinIdentifer" forKey: (__bridge id)kSecAttrAccount];

    //no pin set
    if([[pinWrapper objectForKey:(__bridge id)(kSecValueData)] length] == 0)
    {
        UIAlertView* dialog = [[UIAlertView alloc] init];
        dialog.tag = kEnterNewPinAlert;
        [dialog setDelegate:self];
        [dialog setTitle:@"Wprowadź nowy PIN"];
        [dialog setMessage:@"\n\n\n"];
        [dialog addButtonWithTitle:@"OK"];
        
        pinField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
        [pinField setPlaceholder:@"Wprowadź PIN"];
        [pinField setSecureTextEntry: YES];
        [pinField setKeyboardType:UIKeyboardTypeNumberPad];
        [pinField setBackgroundColor:[UIColor whiteColor]];
        [dialog addSubview:pinField];
        
        pinFieldRepeat = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 80.0, 245.0, 25.0)];
        [pinFieldRepeat setPlaceholder:@"Powtórz PIN"];
        [pinFieldRepeat setSecureTextEntry: YES];
        [pinFieldRepeat setKeyboardType:UIKeyboardTypeNumberPad];
        [pinFieldRepeat setBackgroundColor:[UIColor whiteColor]];
        [dialog addSubview:pinFieldRepeat];

        [dialog show];
        
        [pinField becomeFirstResponder];
    }
    
    //pin already set
    else
    {
        UIAlertView* dialog = [[UIAlertView alloc] init];
        dialog.tag = kEnterExistingPinAlert;
        [dialog setDelegate:self];
        [dialog setTitle:@"Wprowadź PIN"];
        [dialog setMessage:@" "];
        [dialog addButtonWithTitle:@"OK"];
        
        pinField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
        [pinField setPlaceholder:@"Wprowadź PIN"];
        [pinField setSecureTextEntry: YES];
        [pinField setKeyboardType:UIKeyboardTypeNumberPad];
        [pinField setBackgroundColor:[UIColor whiteColor]];
        [dialog addSubview:pinField];
    
        [dialog show];
        
        [pinField becomeFirstResponder];
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == kEnterExistingPinAlert)
    {
        //pin number entered was correct
        if([pinField.text isEqualToString: [pinWrapper objectForKey:(__bridge id)(kSecValueData)]])
        {
            KeychainItemWrapper *secureDataKeychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"com.ICF.keychain.securedData" accessGroup:nil];
            NSString *secureDataString = [secureDataKeychain objectForKey:(__bridge id)(kSecValueData)];
            
            //we have stored data for this keychain
            if([secureDataString length] != 0)
            {
                NSData* data = [secureDataString dataUsingEncoding:NSUTF8StringEncoding];
                
                NSError *error = nil;
                NSDictionary *secureDataDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                
                if(error != nil)
                {
                    NSLog(@"Wystąpił błąd: %@", [error localizedDescription]);
                }
                
                numberTextField.text = [secureDataDictionary objectForKey:@"numberTextField"];
                expDateTextField.text = [secureDataDictionary objectForKey:@"expDateTextField"];
                CV2CodeTextField.text = [secureDataDictionary objectForKey:@"CV2CodeTextField"];
                nameTextField.text = [secureDataDictionary objectForKey:@"nameTextField"];
            }
            
            else
            {
                NSLog(@"Nie przechowano danych pęku kluczy!");
            }
        }
        
        //pin entered was incorrect
        else
        {
            UIAlertView* dialog = [[UIAlertView alloc] init];
            dialog.tag = kEnterExistingPinAlert;
            [dialog setDelegate:self];
            [dialog setTitle:@"Nieprawidłowy Pin!"];
            [dialog setMessage:@" "];
            [dialog addButtonWithTitle:@"OK"];
            
            pinField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
            [pinField setPlaceholder:@"Wprowadź PIN"];
            [pinField setSecureTextEntry: YES];
            [pinField setKeyboardType:UIKeyboardTypeNumberPad];
            [pinField setBackgroundColor:[UIColor whiteColor]];
            [dialog addSubview:pinField];
            
            [dialog show];
            
            [pinField becomeFirstResponder];
        }
    }
    
    else
    {
        if([pinField.text isEqualToString: pinFieldRepeat.text])
        {
            [pinWrapper setObject:[pinField text] forKey:(__bridge id)(kSecValueData)];
        }
            
        else
        {
            UIAlertView* dialog = [[UIAlertView alloc] init];
            dialog.tag = kEnterNewPinAlert;
            [dialog setDelegate:self];
            [dialog setTitle:@"PIN-y nie zgadzają się!!"];
            [dialog setMessage:@"\n\n\n"];
            [dialog addButtonWithTitle:@"OK"];
            
            pinField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
            [pinField setPlaceholder:@"Wprowadź PIN"];
            [pinField setSecureTextEntry: YES];
            [pinField setKeyboardType:UIKeyboardTypeNumberPad];
            [pinField setBackgroundColor:[UIColor whiteColor]];
            [dialog addSubview:pinField];
            
            pinFieldRepeat = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 80.0, 245.0, 25.0)];
            [pinFieldRepeat setPlaceholder:@"Powtórz PIN"];
            [pinFieldRepeat setSecureTextEntry: YES];
            [pinFieldRepeat setKeyboardType:UIKeyboardTypeNumberPad];
            [pinFieldRepeat setBackgroundColor:[UIColor whiteColor]];
            [dialog addSubview:pinFieldRepeat];
            
            [dialog show];
            
            [pinField becomeFirstResponder];
        }
    }
}

- (IBAction)save:(id)sender
{
    NSMutableDictionary *secureDataDict = [[NSMutableDictionary alloc] init];
    NSError *error = nil;
    
    if(numberTextField.text)
        [secureDataDict setObject:numberTextField.text forKey:@"numberTextField"];
    if(expDateTextField.text)
        [secureDataDict setObject:expDateTextField.text forKey:@"expDateTextField"];
    if(CV2CodeTextField.text)
        [secureDataDict setObject:CV2CodeTextField.text forKey:@"CV2CodeTextField"];
    if(nameTextField.text)
        [secureDataDict setObject:nameTextField.text forKey:@"nameTextField"];
    
    NSData *rawData = [NSJSONSerialization dataWithJSONObject:secureDataDict
                                                       options:0
                                                         error:&error];
    if(error != nil)
    {
        NSLog(@"Wystąpił błąd: %@", [error localizedDescription]);
    }
    
    NSString *dataString = [[NSString alloc] initWithData:rawData encoding:NSUTF8StringEncoding];
    KeychainItemWrapper *secureDataKeychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"com.ICF.keychain.securedData" accessGroup:nil];
    [secureDataKeychain setObject:@"secureDataIdentifer" forKey: (__bridge id)kSecAttrAccount];
    [secureDataKeychain setObject:(__bridge id)(kSecAttrAccessibleWhenUnlocked) forKey: (__bridge id)kSecAttrAccessible];
    [secureDataKeychain setObject:dataString forKey:(__bridge id)(kSecValueData)];
    
}



@end
