#import "TerminalSettingsViewController.h"

@interface TerminalSettingsViewController()<UITabBarControllerDelegate>
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UIButton *getSettingsButton;
@property (weak, nonatomic) IBOutlet UIButton *createSettingsButton;
@property (weak, nonatomic) IBOutlet UIButton *updateSettingsButton;
@property (weak, nonatomic) IBOutlet UIButton *deleteSettingsButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end


@implementation TerminalSettingsViewController
{
    UIColor* color;
    NSMutableArray *tableData;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.delegate = self;
    color = UIColorFromRGB(0xC11D03);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(openSettings)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    [self setTheme];
    [self setMode];
    tableData = [[NSMutableArray alloc] init];
}

- (void)viewWillAppear:(BOOL)animated{
    [[WTPSTerminal singleton] registerCoreAPISettingsListener:self];
    [[WTPSTerminal singleton] registerCoreAPIMessageListener:self];
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    if(![viewController.restorationIdentifier isEqualToString:@"terminalSettingsViewControllerNavigation"]){
        [[WTPSTerminal singleton] unRegisterCoreAPISettingsListener:self];
        [[WTPSTerminal singleton] unRegisterCoreAPIMessageListener:self];
    }
}

- (void) setTheme{
    self.navigationController.navigationBar.barTintColor = color;
    self.tabBarController.tabBar.tintColor = color;
}

- (void) setMode{
    NSString* mode = [Util getFromSettings:@"mode"];
    if(mode != nil){
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:mode style:UIBarButtonItemStylePlain target:self action:nil];
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    }
}

- (void) openSettings{
    UINavigationController *settings = [[UIStoryboard storyboardWithName:@"Mainview" bundle:nil] instantiateViewControllerWithIdentifier:@"appSettingsViewControllerNavigation"];
    [self presentViewController:settings animated:YES completion:nil];
}

- (void)viewDidAppear:(BOOL)animated{
    self.tabBarController.tabBar.tintColor = color;
    [self setMode];
}

- (IBAction)getSettingsHandle:(id)sender {
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
    [[WTPSTerminal singleton] retrieveSettings];
}

- (IBAction)createSettingsHandle:(id)sender {
    CoreTerminalUpdate *terminalUpdate = [[CoreTerminalUpdate alloc] init];
    CoreTax* tax = [[CoreTax alloc] init];
    tax.percentage = [NSNumber numberWithDouble: 12.4];
    tax.name = @"Test IOS CREATE TEST";
    
    CoreTip* tip = [[CoreTip alloc] init];
    tip.percentage = [NSNumber numberWithDouble: 23.421];
    tip.tipType = @"PERCENTAGE";
    
    [terminalUpdate.settingsCreate addObject:tax];
    [terminalUpdate.settingsCreate addObject:tip];
    [[WTPSTerminal singleton] updateSettings:terminalUpdate];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
}

- (IBAction)updateSettingsHandle:(id)sender {
    CoreTerminalUpdate *terminalUpdate = [[CoreTerminalUpdate alloc] init];
    CoreSettings* settings  = [[WTPSTerminal singleton] getSettings];
    if (settings.taxListArray != nil && [settings.taxListArray count] > 0) {
        CoreTax* taxUpdate = [settings.taxListArray objectAtIndex:0];
        taxUpdate.name = @"Test 1 update";
        [terminalUpdate.settingsUpdate addObject:taxUpdate];
    }
    if (settings.tipListArray != nil && [settings.tipListArray count] > 0) {
        CoreTip* tipUpdate = [settings.tipListArray objectAtIndex:0];
        tipUpdate.percentage = [NSNumber numberWithDouble: 3.642];
        [terminalUpdate.settingsUpdate addObject:tipUpdate];
    }
    
    [[WTPSTerminal singleton] updateSettings:terminalUpdate];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
}

- (IBAction)deleteSettingsHandle:(id)sender {
    CoreTerminalUpdate *terminalUpdate = [[CoreTerminalUpdate alloc] init];
    CoreSettings* settings  = [[WTPSTerminal singleton] getSettings];
    if (settings.taxListArray != nil && [settings.taxListArray count] > 0) {
        CoreTax* taxDelete = [settings.taxListArray objectAtIndex:0];
        [terminalUpdate.settingsDelete addObject:taxDelete];
    }
    if (settings.tipListArray != nil && [settings.tipListArray count] > 0) {
        CoreTip* tipDelete = [settings.tipListArray objectAtIndex:0];
        [terminalUpdate.settingsDelete addObject:tipDelete];
    }
    
    [[WTPSTerminal singleton] updateSettings:terminalUpdate];
    [[UiHelper singleton] showLoading:self.view isDeviceSale:NO];
    
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CardCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"cardCell"];
    
    if (cell == nil) {
        cell = [[CardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cardCell"];
    }
    
    TableData *data = [tableData objectAtIndex:indexPath.row];
    cell.name.text = data.firstDescription;
    cell.amount.text = data.firstRightDescription;
    cell.cardNumber.text = data.secondDescription;
    cell.date.text = data.secondRightDescrition;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

#pragma mark ------------- CoreAPIListener --------------

/*!
 * This method is triggered after error has occurred in the SDK.
 * @param error contains typedef enum of an error.
 */
-(void)onError:(CoreError) error withDescription:(NSString*) message{
    NSString* errorValue = [Util parseCoreError:error withMessage:message];
    [_statusLabel setText:errorValue];
    [[UiHelper singleton] showError:errorValue];
}

/*!
 * Contains message coming from the SDK while processing the transaction.
 * @param message enum value of a message
 */
-(void)onMessage:(CoreMessage)message{
    NSString* messageValue = [Util parseCoreMessage:message];
    [[UiHelper singleton] toastMessage:messageValue];
    [_statusLabel setText:messageValue];
}

/*!
 * Sends back terminal settings object in response to init method.
 * @param settings holds the settings
 */
-(void)onSettingsRetrieved:(CoreSettings*)settings{
    [[UiHelper singleton] hideLoading];
    tableData = [[NSMutableArray alloc] init];
    if (settings.merchantDetails != nil){
        TableData* rowName = [[TableData alloc] init];
        rowName.firstDescription = @"Name";
        rowName.secondDescription = settings.merchantDetails.name;
        [tableData addObject:rowName];
        
        TableData* rowAddress = [[TableData alloc] init];
        rowAddress.firstDescription = @"Address";
        rowAddress.secondDescription = settings.merchantDetails.address1;
        [tableData addObject:rowAddress];
        
        TableData* rowCountry = [[TableData alloc] init];
        rowCountry.firstDescription = @"Country";
        rowCountry.secondDescription = settings.merchantDetails.country;
        [tableData addObject:rowCountry];
        
        TableData* rowCity = [[TableData alloc] init];
        rowCity.firstDescription = @"City";
        rowCity.secondDescription = settings.merchantDetails.city;
        [tableData addObject:rowCity];
        
        TableData* rowPhone = [[TableData alloc] init];
        rowPhone.firstDescription = @"Phone";
        rowPhone.secondDescription = settings.merchantDetails.phone;
        [tableData addObject:rowPhone];
    }
    
    if (settings.features != nil){
        for (id key in settings.features) {
            TableData* rowFeature = [[TableData alloc] init];
            rowFeature.firstDescription = @"Feature";
            rowFeature.secondDescription = key;
            rowFeature.secondRightDescrition = [settings.features objectForKey:key] ? @"true" : @"false";
            [tableData addObject:rowFeature];
        }
    }
    
    if(settings.taxListArray !=nil && settings.tipListArray != nil){
        for (int i=0; i < [settings.taxListArray count]; i++) {
            CoreTax* tax = [settings.taxListArray objectAtIndex:i];
            TableData* rowTax = [[TableData alloc] init];
            rowTax.firstDescription = @"TAX";
            rowTax.firstRightDescription = tax.name;
            rowTax.secondDescription = [NSString stringWithFormat:@"Percentage: %@",  tax.percentage];
            rowTax.secondRightDescrition = [NSString stringWithFormat:@"UID: %@",  tax.uid];
            [tableData addObject:rowTax];
        }
        
        for (int i=0; i < [settings.tipListArray count]; i++) {
            CoreTip* tip = [settings.tipListArray objectAtIndex:i];
            TableData* rowTax = [[TableData alloc] init];
            rowTax.firstDescription = @"TIP";
            rowTax.firstRightDescription = [NSString stringWithFormat:@"TypType: %@",  tip.tipType];
            rowTax.secondDescription = [NSString stringWithFormat:@"Amount: %@",  tip.amount];
            rowTax.secondRightDescrition = [NSString stringWithFormat:@"Percentage: %@",  tip.percentage];
            [tableData addObject:rowTax];
        }
    }
    [_tableView reloadData];
    [_statusLabel setText:@"Settings retrieved"];
}

@end
