//
//  AccountSettingsViewController.m
//  OpenStack
//
//  Created by Mike Mayo on 12/14/10.
//  The OpenStack project is provided under the Apache 2.0 license.
//

#import "AccountSettingsViewController.h"
#import "OpenStackAccount.h"
#import "Provider.h"
#import "RSTextFieldCell.h"
#import "UIColor+MoreColors.h"
#import "OpenStackAppDelegate.h"
#import "UIViewController+Conveniences.h"
#import "OpenStackRequest.h"

#define kUsername 0
#define kAPIKey 1

@implementation AccountSettingsViewController

@synthesize account, userName, apiKey, activityIndicatorView;

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) || (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark HTTP Response Handlers

- (void)authenticationSucceded:(OpenStackRequest *)request {
    
    [self.activityIndicatorView removeFromSuperview];

    if ([request isSuccess]) {        
        account.authToken = [[request responseHeaders] objectForKey:@"X-Auth-Token"];
        account.serversURL = [NSURL URLWithString:[[request responseHeaders] objectForKey:@"X-Server-Management-Url"]];
        
        NSString *filesStorageURL;
        if (![[request responseHeaders] objectForKey:@"X-Storage-URL"]) {
            filesStorageURL = [NSString stringWithFormat:@"%@/v1/%@",
                               [account.hostURL absoluteString],
                               [account username]];
            account.filesURL = [NSURL URLWithString:filesStorageURL];
        }
        else {
            account.filesURL = [NSURL URLWithString:[[request responseHeaders] objectForKey:@"X-Storage-Url"]];
        }
        
        account.pithosPublicLinkURLPrefix = account.hostURL;
        account.pithosLoginURLPrefix = [NSURL URLWithString:
                                        [[account.hostURL absoluteString]
                                         stringByAppendingString:@"/login"]];

        NSString *cdnStr = [[request responseHeaders] objectForKey:@"X-Cdn-Management-Url"];
        if (!cdnStr) {
            cdnStr = [[request responseHeaders] objectForKey:@"X-CDN-Management-Url"];
        }
        if (cdnStr) {
            account.cdnURL = [NSURL URLWithString:cdnStr];
        }
        [account persist];
        [account refreshCollections];
        [self.navigationController dismissModalViewControllerAnimated:YES];
    } else {
        self.navigationItem.rightBarButtonItem.enabled = NO;
        [self alert:@"Authentication Failure" message:@"Please check your User Name and Token."];
    }
}

- (void)authenticationFailed:(OpenStackRequest *)request {
    [self.activityIndicatorView removeFromSuperview];
    self.navigationItem.rightBarButtonItem.enabled = YES;
    self.account.containers = nil;
    if ([request responseStatusCode] == 401) {
        [self alert:@"Authentication Failure" message:@"Please check your User Name and Token."];
    } else {
        [self failOnBadConnection];
    }
}


- (void)authenticate {
    
    BOOL valid = YES;
    
        valid = valid && usernameTextField.text && ![@"" isEqualToString:usernameTextField.text];
        if (!valid) {
            [self alert:nil message:@"Please enter your username."];
            [usernameTextField becomeFirstResponder];
        } else {
            valid = valid && apiKeyTextField.text && ![@"" isEqualToString:apiKeyTextField.text];
            if (!valid) {
                [self alert:nil message:@"Please enter your token."];
                [apiKeyTextField becomeFirstResponder];
            } else {
                account.username = usernameTextField.text;
                account.apiKey = apiKeyTextField.text;                        
                
                self.activityIndicatorView = [[[ActivityIndicatorView alloc] initWithFrame:[ActivityIndicatorView frameForText:@"Authenticating..."] text:@"Authenticating..."] autorelease];
                [self.activityIndicatorView addToView:self.view];
                
                OpenStackRequest *request = [OpenStackRequest authenticationRequest:account];
                request.delegate = self;
                request.didFinishSelector = @selector(authenticationSucceded:);
                request.didFailSelector = @selector(authenticationFailed:);
                [request startAsynchronous];
            }
        }
}



#pragma mark -
#pragma mark Button Handlers

- (void)saveButtonPressed:(id)sender {
    [self authenticate];
}


#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"API Account Info";
    userDetailsSection = 0;
    if ([self.account.provider isGRNet])
        getTokenSection = 1;
    else
        getTokenSection = -1;
    
    /*if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        UIView *backgroundContainer = [[UIView alloc] init];
        backgroundContainer.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        backgroundContainer.backgroundColor = [UIColor iPadTableBackgroundColor];
        NSString *logoFilename = @"account-settings-icon-large.png";
        UIImageView *osLogo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:logoFilename]];
        osLogo.contentMode = UIViewContentModeScaleAspectFit;
        osLogo.frame = CGRectMake(100.0, 100.0, 1000.0, 1000.0);
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            osLogo.alpha = 0.3;
        }
        [backgroundContainer addSubview:osLogo];
        [osLogo release];
        self.tableView.backgroundView = backgroundContainer;
        [backgroundContainer release];
    }   */ 
    
    [self addSaveButton];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];    
    //[usernameTextField becomeFirstResponder];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (getTokenSection > 0)
        return 2;
    else
        return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == userDetailsSection)
        return 2;
    else
        return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == userDetailsSection)
        return [NSString stringWithFormat:@"%@ Login", self.account.provider.name];
    else 
        return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    if (section == userDetailsSection)
        return [NSString stringWithFormat:@"API Version %@", self.account.apiVersion];
    else
        return nil;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    RSTextFieldCell *cell = nil;
    if (indexPath.section == userDetailsSection) {
        cell = (RSTextFieldCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[RSTextFieldCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            cell.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.8];
        }

        [cell.textLabel setBackgroundColor:[UIColor clearColor]];

        if (indexPath.row == kUsername) {
            cell.textLabel.text = @"Username";
            usernameTextField = cell.textField;
            usernameTextField.delegate = self;
            usernameTextField.secureTextEntry = NO;
            usernameTextField.returnKeyType = UIReturnKeyNext;
            usernameTextField.text = self.account.username;
            usernameTextField.placeholder = @"username";
            if (userName)
                usernameTextField.text = userName;
        } else if (indexPath.row == kAPIKey) {
            cell.textLabel.text = @"Token";
            apiKeyTextField = cell.textField;
            apiKeyTextField.secureTextEntry = YES;
            apiKeyTextField.delegate = self;
            apiKeyTextField.returnKeyType = UIReturnKeyDone;
            apiKeyTextField.text = self.account.apiKey;
            if (apiKey)
                apiKeyTextField.text = apiKey;
        }
    } else {
        cell = (RSTextFieldCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[RSTextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
        
        cell.textLabel.text = @"Get Token";
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == getTokenSection) {
        NSString *loginURL = [NSString stringWithFormat:@"%@?next=pithos://login", account.pithosLoginURLPrefix]; 
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:loginURL]];
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
}

#pragma mark - Text Field Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {    
    [textField resignFirstResponder];    
    if ([textField isEqual:usernameTextField]) {
        [apiKeyTextField becomeFirstResponder];
    }
    return NO;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *result = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([textField isEqual:usernameTextField]) {
        self.account.username = result;
    } else if ([textField isEqual:apiKeyTextField]) {
        self.account.apiKey = result;
    }
    self.account.authToken = @"";
    self.account.hasBeenRefreshed = NO;
    [self.account persist];
    
    return YES;
}

#pragma mark - Memory management

- (void)dealloc {
    [userName release];
    [apiKey release];
    [activityIndicatorView release];
    [account release];
    [super dealloc];
}


@end

