//
//  AccountGroupsViewController.m
//  pithos-ios
//
// Copyright 2011 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 "AccountGroupsViewController.h"
#import "AccountManager.h"
#import "OpenStackRequest.h"
#import "EditAccountGroupsViewController.h"
#import "UIViewController+Conveniences.h"
#import "NSString+Conveniences.h"
#import "APICallback.h"


@implementation AccountGroupsViewController

@synthesize account, groups;


- (void)dealloc
{
    [account release];
    [groups release];
    [metadata release];
    [super dealloc];
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"Groups";
    groups = [[NSMutableDictionary alloc] init];
    metadata = [[NSMutableDictionary alloc] init];
    
    NSString *activityMessage = @"Loading..";
    activityIndicatorView = [[ActivityIndicatorView alloc] initWithFrame:[ActivityIndicatorView frameForText:activityMessage] text:activityMessage];
    [activityIndicatorView addToView:self.view];
    
    [[self.account.manager getStorageAccountInfo] 
     success:^(OpenStackRequest *request) {
         [activityIndicatorView removeFromSuperviewAndRelease];
         for (NSString *key in request.responseHeaders) {
             if ([key hasPrefix:@"X-Account-Group-"]) {
                 NSString *groupUsers = [NSString decodeFromPercentEscape:[request.responseHeaders objectForKey:key]];
                 NSString *groupName = [NSString decodeFromPercentEscape:[key substringFromIndex:16]];
                 [groups setObject:groupUsers forKey:groupName];
             }
         }
         
         for (NSString *header in request.responseHeaders) {
             if ([header hasPrefix:@"X-Account-Meta-"])  {
                 NSString *metadataKey = [NSString decodeFromPercentEscape:[header substringFromIndex:15]];
                 NSString *metadataValue = [NSString decodeFromPercentEscape:[request.responseHeaders objectForKey:header]];
                 [metadata setObject:metadataValue forKey:metadataKey];
             }
         }

         [self.tableView reloadData];

     }
     failure:^(OpenStackRequest *request) {
         [activityIndicatorView removeFromSuperviewAndRelease];
         [self alert:@"Error" message:@"Failed to get account information"];
     }];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

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

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

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

#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [groups count] + 1;
}

- (CGFloat)findLabelHeight:(NSString*)text font:(UIFont *)font {
    CGSize textLabelSize;    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        // 616, 678
        textLabelSize = CGSizeMake(596.0, 9000.0f);
    } else {
        textLabelSize = CGSizeMake(280.0, 9000.0f);
    }
    CGSize stringSize = [text sizeWithFont:font constrainedToSize:textLabelSize lineBreakMode:UILineBreakModeCharacterWrap];
    return stringSize.height;
}

- (CGFloat)tableView:(UITableView *)aTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat result = aTableView.rowHeight;
    
    if ([groups count] > 0 && indexPath.row < [groups count]) {
        NSString *groupName = [[groups allKeys] objectAtIndex:indexPath.row];
        NSString *groupUsers = [groups objectForKey:groupName];
        
        result = 22.0 + [self findLabelHeight:[NSString stringWithFormat:@"%@", groupUsers] font:[UIFont systemFontOfSize:18.0]];
    
        return MAX(aTableView.rowHeight, result);
    }
    return aTableView.rowHeight;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.row < [groups count]) {
        NSString *groupName = [[groups allKeys] objectAtIndex:indexPath.row];
        cell.textLabel.text = groupName;
        cell.detailTextLabel.text = [groups objectForKey:groupName];
        cell.detailTextLabel.numberOfLines = 0;
        cell.detailTextLabel.lineBreakMode = UILineBreakModeCharacterWrap;
    }
    else {
        cell.textLabel.text = @"Add Group";
        cell.detailTextLabel.text = @"";
    }
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    EditAccountGroupsViewController *vc = [[EditAccountGroupsViewController alloc] initWithNibName:@"EditAccountGroupsViewController" bundle:nil];
    
    vc.account = self.account;
    vc.metadata = metadata;
    vc.groups = groups;
    if (indexPath.row < [groups count]) {        
        NSString *groupName = [[groups allKeys] objectAtIndex:indexPath.row];
        NSString *groupUsers = [groups objectForKey:groupName];
        
        vc.removeGroupEnabled = YES;
        vc.groupName = groupName;
        vc.groupUsers = groupUsers;
        vc.navigationItem.title = @"Edit Group";
    }
    else {
        vc.removeGroupEnabled = NO;
        vc.groupName = @"";
        vc.groupUsers = @"";
        vc.navigationItem.title = @"Add Group";
    }
    
    [self.navigationController pushViewController:vc animated:YES];
    [vc release];
}


@end
