//
//  GMSDMenuFormViewController.m
//  GMS Sample
//
/*
 Version: 1.0
 
 Disclaimer: IMPORTANT:  This software is supplied to you by Genesys
 Telecommunications Laboratories Inc ("Genesys") in consideration of your agreement
 to the following terms, and your use, installation, modification or redistribution
 of this Genesys software constitutes acceptance of these terms.  If you do not
 agree with these terms, please do not use, install, modify or redistribute this
 Genesys software.
 
 In consideration of your agreement to abide by the following terms, and subject
 to these terms, Genesys grants you a personal, non-exclusive license, under
 Genesys's copyrights in this original Genesys software (the "Genesys Software"), to
 use, reproduce, modify and redistribute the Genesys Software, with or without
 modifications, in source and/or binary forms; provided that if you redistribute
 the Genesys Software in its entirety and without modifications, you must retain
 this notice and the following text and disclaimers in all such redistributions
 of the Genesys Software.
 
 Neither the name, trademarks, service marks or logos of Genesys Inc. may be used
 to endorse or promote products derived from the Genesys Software without specific
 prior written permission from Genesys.  Except as expressly stated in this notice,
 no other rights or licenses, express or implied, are granted by Genesys herein,
 including but not limited to any patent rights that may be infringed by your
 derivative works or by other works in which the Genesys Software may be
 incorporated.
 
 The Genesys Software is provided by Genesys on an "AS IS" basis.  GENESYS MAKES NO
 WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
 WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 PURPOSE, REGARDING THE GENESYS SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
 COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL GENESYS BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
 DISTRIBUTION OF THE GENESYS SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
 CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
 GENESYS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 Copyright (C) 2013 Genesys Inc. All Rights Reserved.
 */

#import "GMSDMenu.h"
#import "GMSDMenuFormViewController.h"
#import "GMSDMenuFormCell.h"
#import "GMSDMenuFormMultiViewController.h"
#import "UIAlertViewBlock.h"

@interface GMSDMenu ()
- (void) jumpBefore:(NSString *)id2Jump;
@end


@implementation GMSDMenuFormViewController
{
    // instance variables declared in implementation context
    NSMutableDictionary *paramValues;
    
    NSDictionary *menuDictionary;
    NSString *iD;
    NSString *menuLabel;
    NSString *audioURL;
    NSString *sectionTitle;
    NSString *userActionURL;
    NSString *submitBtnTitle;
    NSString *method;
    NSString *iDToJumpBefore;
    NSDictionary *confirmationDialog;
    NSArray *formContent;
    
    GMSDMenu __weak *dMenuDelegate;
}

+ (GMSDMenuFormViewController *)initWithObject:(NSDictionary *)vObject parentObject:(NSDictionary *)parent dMenuDelegate:(GMSDMenu *)delegate
{
    GMSDMenuFormViewController *vIVR = [[GMSDMenuFormViewController alloc] initWithStyle:UITableViewStyleGrouped];
    vIVR->menuDictionary = vObject;
    vIVR->iD = vObject[@"_dialog_id"];
    vIVR->menuLabel = vObject[@"_label"];
    vIVR->audioURL = vObject[@"_audio_url"];
    vIVR->sectionTitle = vObject[@"_section_title"];
    vIVR->submitBtnTitle = vObject[@"_submit_button_title"];
    vIVR->iDToJumpBefore = vObject[@"_id_to_jump_before"];
    vIVR->confirmationDialog = vObject[@"_confirmation_dialog"];
    vIVR->formContent = vObject[@"_content"];

    
    //UserActionURL, method, parameterName and action are inherited from parent, but may be overwritten
    vIVR->userActionURL = (vObject[@"_user_action_url"]) ? vObject[@"_user_action_url"] : parent[@"_user_action_url"];
    vIVR->method = (vObject[@"_method"]) ? vObject[@"_method"] : parent[@"_method"];
    
    vIVR.tableView.dataSource = vIVR;
    vIVR.tableView.delegate = vIVR;
    
    vIVR->dMenuDelegate = delegate;

    return vIVR;
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    paramValues = [NSMutableDictionary dictionaryWithObject:iD forKey:@"_dialog_id"];
    [formContent enumerateObjectsUsingBlock:^(id x, NSUInteger index, BOOL *stop){
        [paramValues setValue:x[@"_parameter_value"] forKey:x[@"_parameter_name"]];
    }];

    UILabel *tlabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 300, 40)];
    tlabel.text = menuLabel;
    tlabel.textColor = [UIColor whiteColor];
    tlabel.backgroundColor = [UIColor clearColor];
    tlabel.font = [UIFont boldSystemFontOfSize:18.0];
    tlabel.textAlignment = NSTextAlignmentCenter;
    tlabel.adjustsFontSizeToFitWidth = YES;
    self.navigationItem.titleView = tlabel;
   
    NSString *btnTitle = (submitBtnTitle) ? submitBtnTitle : @"Submit";
    UIBarButtonItem *exitButton = [[UIBarButtonItem alloc] initWithTitle:btnTitle
                                                                   style:UIBarButtonItemStylePlain
                                                                  target:self
                                                                  action:@selector(submitForm:)];
    self.navigationItem.rightBarButtonItem = exitButton;
}

- (void)viewDidUnLoad
{
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;

    paramValues = nil;
    iD = nil;
    menuLabel =nil;
    audioURL = nil;
    userActionURL = nil;
    method = nil;
    iDToJumpBefore = nil;
    confirmationDialog = nil;
    formContent = nil;
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return sectionTitle;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return formContent.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MultiCellIdentifier = @"MultiSelectCell";
    static NSString *TextCellIdentifier = @"TextSelectCell";
    NSString *action = (formContent[indexPath.row])[@"_action"];
    
    GMSDMenuFormCell *cell;

    // Configure the cell...
    if ([action isEqualToString:@"MultiChoice"]) {
        cell = [tableView dequeueReusableCellWithIdentifier:MultiCellIdentifier];
        if (cell == nil) {
            cell = (GMSDMenuFormCell *)[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier:MultiCellIdentifier];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = (formContent[indexPath.row])[@"_label"];
        cell.detailTextLabel.text = paramValues[(formContent[indexPath.row])[@"_parameter_name"]];
        cell.textLabel.adjustsFontSizeToFitWidth = YES;
    }
    else {
        //NumericString or DateString
        cell = [tableView dequeueReusableCellWithIdentifier:TextCellIdentifier];
        if (cell == nil) {
            cell = [GMSDMenuFormCell newCellFromNib:@"GMSDMenuFormCell" paramValues:paramValues cellContent:formContent[indexPath.row]];
       }
    }

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if ([(formContent[indexPath.row])[@"_action"] isEqualToString:@"MultiChoice"]) {
        // Create and push MultiChoice view controller.
         GMSDMenuFormMultiViewController *gmsMulti = [GMSDMenuFormMultiViewController initWithContent:formContent[indexPath.row]
                                                                                                  paramValues:paramValues
                                                                                              parentIndexPath:indexPath
                                                                                                      delegate:self];
         // Pass the selected object to the new view controller.
        [self.navigationController pushViewController:gmsMulti animated:YES];
    }
}

#pragma mark - Submit Form

- (void)submit2GMS
{
    //Submit request to GMS
    [dMenuDelegate jumpBefore:iDToJumpBefore];
    [dMenuDelegate submitRequestWithURL:userActionURL method:method params:paramValues headers:nil completionBlock:nil];
}

- (void)submitForm:(id)sender
{
    if (confirmationDialog) {
        //"OkTitle" button is always present, otherButton is optional
        UIAlertViewBlock *alert = [[UIAlertViewBlock alloc] initWithTitle:@"Message from GMS"
                                                                  message:confirmationDialog[@"_text"]
                                                               completion:^(BOOL okPressed, NSInteger buttonIndex, NSDictionary *txtFieldParams) {
                                                                   if (okPressed) {
                                                                       [self submit2GMS];
                                                                   }
                                                               }
                                                        cancelButtonTitle:confirmationDialog[@"_ok_title"]
                                                        otherButtonTitles:confirmationDialog[@"_cancel_title"], nil];
        [alert show];
    }
    else {
        [self submit2GMS];
    }
}

@end
