//
//  GMSDMenuTableViewController.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 "GMSDMenuTableViewController.h"
#import "GMSDMenuFormViewController.h"
#import "UIAlertViewBlock.h"
#import <AVFoundation/AVFoundation.h>
#import "NSData+Base64.h"
#import "GMSUtil.h"

@interface GMSDMenu ()

- (void) jumpBefore:(NSString *)id2Jump;
- (void)dialNumber:(NSDictionary *)actionDict;
- (void)openURL:(NSDictionary *)actionDict;
- (void)startChat:(NSDictionary *)actionDict;
- (void)endChat;
- (void)showAlert:(NSDictionary *)responseDict
       jumpBefore:(NSString *)jumpBefore
    userActionURL:(NSString *)userActionURL
           method:(NSString *)method;

@end


@implementation GMSDMenuTableViewController
{
    // instance variables declared in implementation context
    NSDictionary *menuDictionary;
    NSString *iD;
    NSString *menuLabel;
    NSString *audioURL;
    NSString *audioUpdateURL;
    NSString *userActionURL;
    NSString *action;
    NSString *method;
    NSString *expiresAt;
    NSString *resourceURL;
    NSArray *menuContent;
    
    UITableView *tableView;
    AVQueuePlayer *avQueuePlayer;
    AVAudioRecorder *avAudioRecorder;
    NSString *recorderFilePath;
    UIBarButtonItem *playButton, *pauseButton, *spaceButton, *recordButtonStart,
                    *recordButtonStop, *recordButtonPlay, *recordButtonUpload, *recordButtonDone;
    NSIndexPath *recordIndexPath;
    UILongPressGestureRecognizer *gestureRecognizer;
    BOOL recordHeader;
    UIImageView *hdrImageView;
    UIView *hdrView;
    BOOL recordingFinished;
    id recordingChangedObserver;
    id playEndedObserver;
    
    GMSDMenu __weak *dMenuDelegate;
}

+ (GMSDMenuTableViewController *)initWithObject:(NSDictionary *)vObject parentObject:(NSDictionary *)parent dMenuDelegate:(GMSDMenu *)gMenu
{
    GMSDMenuTableViewController *vIVR = [[GMSDMenuTableViewController alloc] init];
    vIVR->menuDictionary = vObject;
    vIVR->iD = vObject[@"_dialog_id"];
    vIVR->menuLabel = vObject[@"_label"];
    vIVR->audioURL = vObject[@"_audio_url"];
    vIVR->audioUpdateURL = vObject[@"_audio_update_url"];
    vIVR->expiresAt = vObject[@"_expires"];
    vIVR->resourceURL = vObject[@"_resource_url"];
    vIVR->menuContent = 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->action = (vObject[@"_action"]) ? vObject[@"_action"] : parent[@"_action"];
    
    vIVR->dMenuDelegate = gMenu;
    
    return vIVR;
}

#pragma mark -
#pragma mark View LifeCycle

- (void)viewDidLoad
{
    [super viewDidLoad];
        
    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;

    //Create table view - Grouped if "GroupName" is present, otherwise Plain
    UITableViewStyle style = ([(menuContent[0])[@"_group_name"] length] > 0) ? UITableViewStyleGrouped : UITableViewStylePlain;
    tableView = [[UITableView alloc] initWithFrame:self.view.frame style:style];
    tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView reloadData];
    
    self.view = tableView;
    
    playButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay
                                                               target:self
                                                               action:@selector(playButton:)];
    pauseButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause
                                                                target:self
                                                                action:@selector(pauseButton:)];
    recordButtonStart = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"microphone.png"]
                                                   style:UIBarButtonItemStylePlain
                                                  target:self
                                                  action:@selector(recordButtonStart:)];
    
    recordButtonStop = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"stop.png"]
                                                         style:UIBarButtonItemStylePlain
                                                        target:self
                                                        action:@selector(recordButtonStop:)];

    recordButtonPlay = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay
                                                               target:self
                                                               action:@selector(recordButtonPlay:)];
    
    recordButtonUpload = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                                                     target:self
                                                                     action:@selector(recordButtonUpload:)];
    
    recordButtonDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop
                                                                     target:self
                                                                     action:@selector(recordButtonDone:)];
    
    spaceButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                                 target:nil
                                                                                 action:nil];
    
    gestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap:)];
    gestureRecognizer.minimumPressDuration = 2.;
    
    recordingChangedObserver = [[NSNotificationCenter defaultCenter]
                                addObserverForName:kRecordingChangedNotification
                                object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
                                    [tableView reloadData];
                                }];
    
    avQueuePlayer = [[AVQueuePlayer alloc] init];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
        
    if (audioUpdateURL && dMenuDelegate.audioEnabled && dMenuDelegate.audioRecordEnabled) {
        //Record mode
        
        [tableView addGestureRecognizer:gestureRecognizer];
        hdrImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"microphone.png"]];
        hdrView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, hdrImageView.image.size.height + 20)];
        hdrImageView.center = hdrView.center;
        [hdrView addSubview:hdrImageView];
        tableView.tableHeaderView = hdrView;
    }
    else {
        //Playback mode
        tableView.tableHeaderView = nil;
        if (dMenuDelegate.audioEnabled) {
            self.toolbarItems = @[spaceButton, playButton, spaceButton];
            self.navigationController.toolbarHidden = NO;
        }
        if (audioURL && dMenuDelegate.audioEnabled) {
            [self addPlay:audioURL];
        }
        if (dMenuDelegate.audioAutoPlay) {
            [self playButton:nil];
        }
    }
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
            
    if (dMenuDelegate.audioEnabled) {
        [[NSNotificationCenter defaultCenter] removeObserver:playEndedObserver];
        [self stopButton:nil];
    }
    if (audioUpdateURL && dMenuDelegate.audioEnabled && dMenuDelegate.audioRecordEnabled) {
        //Record mode
        [avAudioRecorder stop];
        [tableView removeGestureRecognizer:gestureRecognizer];
    }
    
    //Delete tmp files
    [self deleteTmpFiles];
    
}


- (void)viewDidUnload {
    
    [[NSNotificationCenter defaultCenter] removeObserver:recordingChangedObserver];
    
    tableView.delegate = nil;
    tableView.dataSource = nil;
    tableView = nil;
    iD = nil;
    menuLabel = nil;
    audioURL = nil;
    audioUpdateURL = nil;
    expiresAt = nil;
    resourceURL = nil;
    menuContent = nil;
    userActionURL = nil;
    method = nil;
    action = nil;
    avQueuePlayer = nil;
    avAudioRecorder = nil;
    pauseButton = nil;
    playButton = nil;
    spaceButton = nil;
    
    [super viewDidUnload];
}


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

#pragma mark - Log

- (void) logRequest:(NSString *)txt2Log direction:(int)dir {
    //Update Log View
    [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateNotification
                                                        object:self
                                                      userInfo:@{@"direction":@(dir), @"text":txt2Log}];
}

#pragma mark - Audio

-(void)deleteTmpFiles {
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSArray *fileArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:nil];
    for (NSString *filename in fileArray)  {
        [fileMgr removeItemAtPath:[NSTemporaryDirectory() stringByAppendingPathComponent:filename] error:nil];
    }
}

- (void)addPlay:(NSString *)audioURLToAdd {
//    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:audioURL]];    

    //Tmp workaround since GMS storage doesn't allow "." in key name, and iOs wants file extension to play
    //NSData *aData = [NSData dataWithContentsOfURL:[NSURL URLWithString:audioURL]];
    
    UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    UIBarButtonItem *loadingView = [[UIBarButtonItem alloc] initWithCustomView:actView];
    self.toolbarItems = @[spaceButton, loadingView, spaceButton];
    [actView startAnimating];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:audioURLToAdd]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:30.0];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *aData, NSError *error) {
                               
                               if (self.navigationController.visibleViewController != self) {
                                   [self deleteTmpFiles];
                               }
                               else {
                                   if ([aData length] > 0 && error == nil) {
                                       NSString *fName = [NSString stringWithFormat:@"%@%@.m4a", NSTemporaryDirectory(), [[audioURLToAdd pathComponents] lastObject]];
                                       [aData writeToFile:fName atomically:YES];
                                       AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:fName]];
                                       [avQueuePlayer insertItem:playerItem afterItem:nil];
                                       
                                       // Register with the notification center for last the player item.
                                       [[NSNotificationCenter defaultCenter] removeObserver:playEndedObserver];
                                       playEndedObserver = [[NSNotificationCenter defaultCenter]
                                                            addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
                                                            object:playerItem queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
                                                                [self.navigationController setToolbarHidden:YES animated:YES];
                                                                //Delete tmp files
                                                                [self deleteTmpFiles];
                                                            }];
                                   }
                                   if (error != nil){
                                       UIAlertView *alert = [[UIAlertView alloc]
                                                             initWithTitle: @"Error downloading audio from GMS Server"
                                                             message: [NSString stringWithFormat:@"URL: %@, Error: %@", audioURLToAdd, error]
                                                             delegate: nil
                                                             cancelButtonTitle:@"OK"
                                                             otherButtonTitles:nil];
                                       [alert show];
                                   }
                                   [actView stopAnimating];
                                   if (dMenuDelegate.audioAutoPlay) {
                                       self.toolbarItems = @[spaceButton, pauseButton, spaceButton];
                                   }
                                   else {
                                       self.toolbarItems = @[spaceButton, playButton, spaceButton];
                                   }
                               }
                            }
     ];
}

- (void)playButton:(id)sender {
    // Init audio with playback capability
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    dMenuDelegate.audioAutoPlay = YES;
    self.toolbarItems = @[spaceButton, pauseButton, spaceButton];
    [avQueuePlayer play];
}

- (void)pauseButton:(id)sender {
    dMenuDelegate.audioAutoPlay = NO;
    self.toolbarItems = @[spaceButton, playButton, spaceButton];
    [avQueuePlayer pause];
}

- (void)stopButton:(id)sender {
    self.navigationController.toolbarHidden = YES;
    [avQueuePlayer removeAllItems];
}

#pragma mark - Audio record

- (NSString *)getRecordFileName {    
    NSString *fName = nil;    
    if (recordHeader) {
        fName = [[audioURL pathComponents] lastObject];
    }
    else if (recordIndexPath) {
        NSArray *groupContent = (menuContent[recordIndexPath.section])[@"_group_content"];
        NSString *aURL = (groupContent[recordIndexPath.row])[@"_audio_url"];
        fName = [[aURL pathComponents] lastObject];
    }
    return fName;
}

- (void)displayRecordControls {
    
    [avQueuePlayer removeAllItems];
    
    recordingFinished = FALSE;
    self.toolbarItems = @[spaceButton, recordButtonStart, spaceButton];
    [self.navigationController setToolbarHidden:NO animated:YES];
    [tableView reloadData];

    // Init audio with record capability
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];
    
    
    // Create a new dated file
    recorderFilePath = [NSString stringWithFormat:@"%@%@.m4a", NSTemporaryDirectory(), [self getRecordFileName]];
    NSDictionary *recordSettings = @{AVFormatIDKey: [NSNumber numberWithInt:kAudioFormatMPEG4AAC],
                                     AVSampleRateKey:[NSNumber numberWithFloat:16000.0],
                                     AVNumberOfChannelsKey:[NSNumber numberWithInt: 1]};
    
    NSError *error;
    avAudioRecorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:recorderFilePath] settings:recordSettings error:&error];
    [avAudioRecorder prepareToRecord];
}

- (void)recordButtonStart:(id)sender {
    self.toolbarItems = @[spaceButton, recordButtonStop, spaceButton];
    self.navigationController.toolbar.tintColor = [UIColor redColor];
    [UIView animateWithDuration:1.
                          delay:0.
                        options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionAllowUserInteraction
                     animations:^{self.navigationController.toolbar.alpha = 0.7;}
                     completion:nil];
    
    [avAudioRecorder record];
    
}

- (void)recordButtonStop:(id)sender {
    self.toolbarItems = @[spaceButton, recordButtonPlay, spaceButton, recordButtonUpload, spaceButton, recordButtonDone, spaceButton];
    self.navigationController.toolbar.alpha = 1.0;
    self.navigationController.toolbar.tintColor = nil;
    [avAudioRecorder stop];
    recordingFinished = TRUE;
}

- (void)recordButtonPlay:(id)sender {

    // Init audio with play capability
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

    
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:recorderFilePath]];
    [avQueuePlayer insertItem:playerItem afterItem:nil];
    [avQueuePlayer play];
}

- (void)recordButtonUpload:(id)sender {
    if (!recordingFinished) {
        return;
    }
    UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    UIBarButtonItem *loadingView = [[UIBarButtonItem alloc] initWithCustomView:actView];
    self.toolbarItems = @[spaceButton, loadingView, spaceButton];
    [actView startAnimating];
    
    //Upload to URL
    NSString *uURL;
    if (recordHeader) {
        uURL = audioUpdateURL;
    }
    else if (recordIndexPath) {
        NSArray *groupContent = (menuContent[recordIndexPath.section])[@"_group_content"];
        uURL = (groupContent[recordIndexPath.row])[@"_audio_update_url"];
    }
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:uURL]
                                      cachePolicy:NSURLRequestUseProtocolCachePolicy
                                  timeoutInterval:30.0];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"multipart/form-data; boundary=--AaB03x" forHTTPHeaderField:@"Content-Type"];
    
    NSMutableData *requestBody = [[NSMutableData alloc] init];
    NSString *part = [NSString stringWithFormat:@"----AaB03x\r\nContent-Disposition: form-data; name=\"%@\"; filename=\"aaa.m4a\"\r\nContent-Type:audio/x-m4a\r\n\r\n", [self getRecordFileName]];
    [requestBody appendData:[part dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[NSData dataWithContentsOfFile:recorderFilePath]];
    [requestBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[@"----AaB03x--" dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:requestBody];
    
    NSString *strBody = [[NSString alloc] initWithData:requestBody encoding:NSASCIIStringEncoding];
    NSString *trimmedBody;
    trimmedBody = ([strBody length] > 350) ? [NSString stringWithFormat:@"%@ ... %@", [strBody substringToIndex:150], [strBody substringFromIndex:[strBody length] - 150]] : strBody;
    [self logRequest:[NSString stringWithFormat:@"Method: POST, URL: %@,\nHeaders: %@\nBody: %@\n", uURL, [request allHTTPHeaderFields], trimmedBody] direction:toGMS];
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               
                               if ([data length] > 0 && error == nil) {
                                   NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   [self logRequest:responseStr direction:fromGMS];
                               }
                               if (error != nil){
                                   UIAlertView *alert = [[UIAlertView alloc]
                                                         initWithTitle: @"Error uploading audio to GMS Server"
                                                         message: [NSString stringWithFormat:@"URL: %@, Error: %@", uURL, error]
                                                         delegate: nil
                                                         cancelButtonTitle:@"OK"
                                                         otherButtonTitles:nil];
                                   [alert show];
                               }
                                [actView stopAnimating];
                                [self recordButtonDone:nil];
                           }
     ];

}

- (void)recordButtonDone:(id)sender {
    
    [avAudioRecorder stop];
    [avAudioRecorder deleteRecording];
    
    recordIndexPath = nil;
    recordHeader = FALSE;
    hdrImageView.image = [UIImage imageNamed:@"microphone.png"];
    [self.navigationController setToolbarHidden:YES animated:YES];
    [tableView reloadData];
}


#pragma mark - Table view data source

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

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return (menuContent[section])[@"_group_name"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSArray *groupContent = (menuContent[section])[@"_group_content"];
    return groupContent.count;
}

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

    // Configure the cell...
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    NSArray *groupContent = (menuContent[indexPath.section])[@"_group_content"];
    cell.textLabel.text = (groupContent[indexPath.row])[@"_label"];
    cell.textLabel.adjustsFontSizeToFitWidth = YES;
    
    NSString *aURL = (groupContent[indexPath.row])[@"_audio_url"];
    NSString *aUpdateURL = (groupContent[indexPath.row])[@"_audio_update_url"];
    cell.imageView.image = nil;
    if (dMenuDelegate.audioEnabled && dMenuDelegate.audioRecordEnabled) {
        if (aUpdateURL) {
            cell.imageView.image = ([indexPath compare:recordIndexPath] == NSOrderedSame) ? [UIImage imageNamed:@"microphone-red.png"] : [UIImage imageNamed:@"microphone.png"];
        }
    }
    else if (aURL && dMenuDelegate.audioEnabled) {
        [self addPlay:aURL];
        }
    
    return cell;
}

#pragma mark - Gesture recognizer delegate
- (void)longTap:(UILongPressGestureRecognizer *)gRecognizer {    
    //Record mode
    CGPoint p = [gRecognizer locationInView:tableView];
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:p];
    if (indexPath) {
        NSArray *groupContent = (menuContent[indexPath.section])[@"_group_content"];
        if ((groupContent[indexPath.row])[@"_audio_update_url"]) {
            recordHeader = FALSE;
            recordIndexPath = indexPath;
            hdrImageView.image = [UIImage imageNamed:@"microphone.png"];
            [self displayRecordControls];
        }
    }
    else {
        CGPoint locationInView = [hdrView convertPoint:p fromView:gRecognizer.view];
        if (CGRectContainsPoint(hdrView.bounds, locationInView) ) {
            // Point lies inside the bounds
            recordHeader = TRUE;
            recordIndexPath = nil;
            hdrImageView.image = [UIImage imageNamed:@"microphone-red.png"];
            [self displayRecordControls];
        }
    }
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tView deselectRowAtIndexPath:indexPath animated:NO];
    
    NSArray *groupContent = (menuContent[indexPath.section])[@"_group_content"];
    NSString *itemAction = (groupContent[indexPath.row])[@"_action"];
    NSString *iDToJumpBefore = (groupContent[indexPath.row])[@"_id_to_jump_before"];
    
    if ([itemAction isEqualToString:@"DisplayMenu"]) {
        GMSDMenuTableViewController *subMenu = [GMSDMenuTableViewController initWithObject:groupContent[indexPath.row]
                                                                              parentObject:menuDictionary
                                                                             dMenuDelegate:dMenuDelegate];
        // Pass the selected vObject to the new view controller.
        [self.navigationController pushViewController:subMenu animated:YES];
    }
    
    else if ([itemAction isEqualToString:@"Form"]) {
        GMSDMenuFormViewController *formMenu = [GMSDMenuFormViewController initWithObject:groupContent[indexPath.row]
                                                                             parentObject:menuDictionary
                                                                            dMenuDelegate:dMenuDelegate];
        // Pass the selected vObject to the new view controller.
        [self.navigationController pushViewController:formMenu animated:YES];
    }
    
    else if ([itemAction isEqualToString:@"MenuItem"]) {
                
        NSString *subMenuURL = (groupContent[indexPath.row])[@"_user_action_url"];
        NSString *URL = ([subMenuURL length] > 0) ? subMenuURL : userActionURL;
        NSString *subMenuMethod = (groupContent[indexPath.row])[@"_method"];
        NSString *itemMethod = ([subMenuMethod length] > 0) ? subMenuMethod : method;
        
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:(groupContent[indexPath.row])[@"_post_parameters"]];
        [params setValue:(groupContent[indexPath.row])[@"_dialog_id"] forKey:@"_dialog_id"];
        
        NSDictionary *cD = (groupContent[indexPath.row])[@"_confirmation_dialog"];
        if (cD) {
            [dMenuDelegate showAlert:cD jumpBefore:iDToJumpBefore userActionURL:URL method:itemMethod];
        }
        else {
            [dMenuDelegate jumpBefore:iDToJumpBefore];
            [dMenuDelegate submitRequestWithURL:URL method:itemMethod params:params headers:nil completionBlock:nil];
        }
    }
    
    else if ([itemAction isEqualToString:@"DialNumber"]) {
        [dMenuDelegate jumpBefore:iDToJumpBefore];
        [dMenuDelegate dialNumber:groupContent[indexPath.row]];
    }
    
    else if ([itemAction isEqualToString:@"OpenURL"]) {
        [dMenuDelegate jumpBefore:iDToJumpBefore];
        [dMenuDelegate openURL:groupContent[indexPath.row]];
    }
    else if ([itemAction isEqualToString:@"StartChat"]) {
        [dMenuDelegate jumpBefore:iDToJumpBefore];
        [dMenuDelegate startChat:groupContent[indexPath.row]];
    }
    else if ([itemAction isEqualToString:@"EndChat"]) {
        [dMenuDelegate jumpBefore:iDToJumpBefore];
        [dMenuDelegate endChat];
    }
}

@end
