//
//  EditPolicyViewController.m
//  pithos-ios
//
// Copyright 2011-2012 GRNET S.A. All rights reserved.
//
// Redistribution and use in source and binary forms, with or
// without modification, are permitted provided that the following
// conditions are met:
// 
//   1. Redistributions of source code must retain the above
//      copyright notice, this list of conditions and the following
//      disclaimer.
// 
//   2. Redistributions in binary form must reproduce the above
//      copyright notice, this list of conditions and the following
//      disclaimer in the documentation and/or other materials
//      provided with the distribution.
// 
// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// 
// The views and conclusions contained in the software and
// documentation are those of the authors and should not be
// interpreted as representing official policies, either expressed
// or implied, of GRNET S.A.

#import "EditPolicyViewController.h"
#import "UIViewController+Conveniences.h"
#import "AccountManager.h"
#import "OpenStackAccount.h"
#import "Container.h"
#import "ActivityIndicatorView.h"
#import "ContainerDetailViewController.h"
#import "ContainersViewController.h"
#import "APICallback.h"

#define kVersioning 0
#define kQuota 1
#define kSavePolicy 2

@implementation EditPolicyViewController

@synthesize account, container, containerDetailViewController;
@synthesize oldVersioning, oldQuota;

- (void)dealloc {
    [account release];
    [container release];
    [oldVersioning release];
    [super dealloc];
}

#pragma mark - Internal

- (void) configVersioningVariables {
    if ([container.versioning rangeOfString:@"auto"].location != NSNotFound) {
        autoVersioning = YES;
        manualVersioning = NO;
        noVersioning = NO;
    } else if ([container.versioning rangeOfString:@"manual"].location != NSNotFound) {
        autoVersioning = NO;
        manualVersioning = YES;
        noVersioning = NO;
    } else if ([container.versioning rangeOfString:@"none"].location != NSNotFound) {
        autoVersioning = NO;
        manualVersioning = NO;
        noVersioning = YES;
    }
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configVersioningVariables];
    self.navigationItem.title = @"Edit policy";
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.oldQuota = container.quota;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) || (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ((section == kVersioning) ? 2 : 1);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    if (indexPath.section == kVersioning) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            cell.textLabel.text = @"Auto";
            if (autoVersioning) 
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            else
                cell.accessoryType = UITableViewCellAccessoryNone;
        } else if (indexPath.row == 1) {
            cell.textLabel.text = @"Manual";
            if (manualVersioning) 
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            else
                cell.accessoryType = UITableViewCellAccessoryNone;
        } else if (indexPath.row == 2) {
            cell.textLabel.text = @"None";
            if (noVersioning)
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            else
                cell.accessoryType = UITableViewCellAccessoryNone;
        }
    } else if (indexPath.section == kQuota) {
        UITextField *textField = nil;
        for (id subView in cell.contentView.subviews) {
            if ([subView isKindOfClass:[UITextField class]]) {
                textField = (UITextField *)subView;
            }
        }
        
        if (textField == nil) {
            CGRect bounds = [cell.contentView bounds];
            CGRect rect = CGRectInset(bounds, 10.0, 10.0);                        
            textField = [[[UITextField alloc] initWithFrame:rect] autorelease];
            [textField setFrame:rect];
        }
        [textField setClearButtonMode:UITextFieldViewModeWhileEditing];
        [textField setBackgroundColor:[UIColor clearColor]];
        [textField setOpaque:YES];
        [textField setAutocorrectionType:UITextAutocorrectionTypeNo];
        [textField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        [textField setDelegate:self];
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        textField.text = [NSString stringWithFormat:@"%u", self.container.quota];
        [cell.contentView addSubview:textField];
        cell.accessoryType = UITableViewCellAccessoryNone;
    } else if (indexPath.section == kSavePolicy) {
        cell.textLabel.text = @"Save";
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == kVersioning)
        return @"Versioning";
    if (section == kQuota)
        return @"Quota";
    return nil;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section != kQuota)
        [self.view endEditing:YES];

    if (indexPath.section == kVersioning) {
        if (indexPath.row == 0) {
            if (!autoVersioning) {
                autoVersioning = YES;
                manualVersioning = NO;
                noVersioning = NO;
            }
        } else if (indexPath.row == 1) {
            if (!manualVersioning) {
                autoVersioning = NO;
                manualVersioning = YES;
                noVersioning = NO;
             }
        } else if (indexPath.row == 2) {
            if (!noVersioning) {
                autoVersioning = NO;
                manualVersioning = NO;
                noVersioning = NO;
            }
        }
        [self.tableView reloadData];
    } else if (indexPath.section == kSavePolicy) {
        NSIndexPath *quotaCellIndexPath = [NSIndexPath indexPathForRow:0 inSection:kQuota];
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:quotaCellIndexPath];
        UITextField *textField = [[cell.contentView subviews] objectAtIndex:0];
        self.container.quota = [textField.text integerValue];
        
        self.oldVersioning = container.versioning;
        
        if (autoVersioning)
            container.versioning = @"auto";
        else if (manualVersioning)
            container.versioning = @"manual";
        else if (noVersioning)
            container.versioning = @"none";
        
        __block ActivityIndicatorView *activityIndicatorView = [ActivityIndicatorView activityIndicatorViewWithText:@"Applying policy..."
                                                                                                       andAddToView:self.view];
        [[self.account.manager writeContainerPolicy:container] 
         success:^(OpenStackRequest *request) {
             [self.tableView reloadData];
             if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)
                 [self.containerDetailViewController.containersViewController refreshButtonPressed:nil];
             [activityIndicatorView stopAnimatingAndRemoveFromSuperview];
             [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
         }
         failure:^(OpenStackRequest *request) {
             container.versioning = self.oldVersioning;
             container.quota = self.oldQuota;
             [self configVersioningVariables];
             [self.tableView reloadData];
             
             [activityIndicatorView stopAnimatingAndRemoveFromSuperview];
             [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
             [self.tableView reloadData];
             [self alert:@"There was a problem applying the policy." request:request];
         }];        
    }
}

#pragma mark - Textfield delegate

- (void)textFieldDidEndEditing:(UITextField *)textField {
    self.oldQuota = container.quota;
    
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setAllowsFloats:NO];
    if (![numberFormatter numberFromString:textField.text]) {
        [self alert:@"Invalid quota value" message:@"Only integers are accepted as valid quota values"];
        textField.text = [NSString stringWithFormat:@"%d", self.oldQuota];
        [self.tableView reloadData];
    } 
    [numberFormatter release];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

@end
