//
//  KTAudioCallViewController.m
//  Kazaktelecom
//
//  Created by aterite on 6/17/14.
//  Copyright (c) 2014 Artur Chernov. All rights reserved.
//

#import "KTAudioCallViewController.h"
#import "KTDtmfMenuCell.h"


@interface KTAudioCallViewController () <UITableViewDelegate, UITableViewDataSource>



@property (nonatomic, strong) IBOutlet UILabel *lblMenuTitle;
@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSDictionary *dtmfMenu;

//@property (nonatomic, strong) IBOutlet UIButton *callButton;

@end

@implementation KTAudioCallViewController

- (void)dealloc
{
    _remoteNumber = nil;
    _lblNumber = nil;
    _dtmfUrlString = nil;
    _dtmfMenu = nil;
    _tableView = nil;
    _lblMenuTitle = nil;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self tableViewAllowsSelection:@NO];

    _dtmfMenu = @{};

   

}

- (void)updateMenu:(NSDictionary *)menu
{
    NSNumber *suspendDelay = menu[@"suspendDelay"];

    NSNumber *activationDelay = menu[@"activationDelay"];

    if ([activationDelay isKindOfClass:[NSNumber class]]) {
        static NSTimer *timer;
        if ([timer isValid]) {
            [timer invalidate];
        }

        timer = [NSTimer scheduledTimerWithTimeInterval:activationDelay.floatValue target:self selector:@selector(proceedMenu:) userInfo:menu repeats:NO];
    }

    if ([suspendDelay isKindOfClass:[NSNumber class]]) {
        [self performSelector:@selector(tableViewAllowsSelection:) withObject:@YES afterDelay:suspendDelay.floatValue];
    } else {
        [self tableViewAllowsSelection:@YES];
    }

    _dtmfMenu = menu;
    if (_dtmfMenu) {
        _lblMenuTitle.text = [_dtmfMenu objectForKey:@"title"];
    }

    [self.tableView reloadData];
}

- (void)proceedMenu:(NSTimer *)timer
{
    NSDictionary *dict = timer.userInfo;
    [timer invalidate];
    timer =nil;

    if ([_dtmfMenu isEqualToDictionary:dict]) {
        [self sendDtmf:0];
        NSArray *submenus = dict[@"items"];
        NSDictionary *submenu = [submenus isKindOfClass:[NSArray class]] ? submenus[0] : nil;
        [self updateMenu:submenu];
    }
}

- (void)showAlert:(NSString *)text
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Ошибка"
                                                        message:[NSString stringWithFormat:@"Не удалось загрузить меню:\n%@", text]
                                                       delegate:nil
                                              cancelButtonTitle:@"Закрыть"
                                              otherButtonTitles:nil];
    [alertView show];
}

- (void)setDtmfUrlString:(NSString *)dtmfUrlString
{
    _dtmfUrlString = dtmfUrlString;
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:_dtmfUrlString]];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            [self showAlert:connectionError.localizedDescription];
        } else {
            if (data) {
                NSError *error;
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
                if (error) {
                    
                    [self showAlert:error.localizedDescription];
                } else {
                    [self updateMenu:result];
                }
            }
        }
    }];
}

- (void)setRemoteNumber:(NSString *)remoteNumber
{
    _remoteNumber = remoteNumber;

  
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.lblNumber.text = _remoteNumber;
}

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


- (IBAction)endCall:(id)sender
{
    UIButton *button = sender;

    button.enabled = NO;

    self.lblNumber.text = @"Вызов завершен";

   

    [self performSelector:@selector(closeMe) withObject:nil afterDelay:2.0f];
}

- (void)closeMe
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)sendDtmf:(int)dtmf
{
   }


#pragma mark - tableView delegate

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = _dtmfMenu[@"items"];
    return [array isKindOfClass:[NSArray class]] ? array.count : 0;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KTDtmfMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KTDtmfMenuCell"];

    NSArray *array = _dtmfMenu[@"items"];

    NSDictionary *currentItem = array[indexPath.row];

    cell.lblTitle.text = currentItem[@"title"];

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self tableViewAllowsSelection:@NO];

    NSArray *array = _dtmfMenu[@"items"];

    NSDictionary *currentItem = [array isKindOfClass:[NSArray class]] ? array[indexPath.row] : nil;

    NSNumber *dtmfCode = currentItem[@"dtmfCode"];

    [self sendDtmf:dtmfCode.intValue];

    [self updateMenu:currentItem];

    [self performSelector:@selector(tableViewAllowsSelection:) withObject:@YES afterDelay:2.0f];
}


- (void)tableViewAllowsSelection:(NSNumber *)value
{
    self.tableView.allowsSelection = value.boolValue;
    if (value.boolValue) {
        self.tableView.backgroundColor = [UIColor whiteColor];
    } else {
        self.tableView.backgroundColor = [UIColor grayColor];
    }
}

@end
