//
//  RegionSettingViewController.m
//  AsReaderLR
//
//  Created by sps on 2020/08/10.
//  Copyright © 2020 asterisk. All rights reserved.
//

#import "RegionSettingViewController.h"
#import "UserData.h"
#import "SystemSetting.h"

@interface RegionSettingViewController (){
    SystemSetting * systemSetting;
    ResultCode result;
}
@property (strong, nonatomic) IBOutlet UITableView *regionTableView;
@property (strong, nonatomic) NSArray *regionList;
@property (assign, nonatomic) NSInteger selectedIndex;
@property (assign, nonatomic) NSInteger selectedRegion;
@property (assign, nonatomic) NSInteger indexNum;
@property (assign, nonatomic) NSInteger receivedRegion;
@property (assign, nonatomic) NSString* currentRegion;
@property (assign, nonatomic) NSRange regionCheck;

@end

@implementation RegionSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(AsReaderGUNDisconnected:) name:@"AsReaderGUNDisconnected" object:nil];
    
    
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.mReader setDelegate:self];
    
    _currentRegion = [appDelegate.mReader regionName];
    self.title =_currentRegion;
    
    
    self.regionList = @[@"USA",@"Australia",@"Japan",@"Brazil",@"Europe"];
    
    _regionTableView.dataSource = self;
    _regionTableView.delegate = self;
    
}


#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _regionList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *regionCellID = @"RegionCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:regionCellID forIndexPath:indexPath];
    cell.textLabel.text = _regionList[indexPath.row];
    return cell;
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNDisconnected" object:nil];
}


- (void)AsReaderGUNDisconnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}


- (void)updateRegion:(int)region regionName:(NSString *)name{
    UIAlertController *alert= [UIAlertController
                                 alertControllerWithTitle:@"Change Region"
                                 message:name
                                 preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action){
        
        [AppDelegate showGlobalProgressHUDWithTitle:@"Please wait (MAX 40s)"];
        result = [appDelegate.mReader changeRegion:region];
        
        [AppDelegate dismissGlobalHUD];
        if(result == ResultNoError){
            //Update Region info
            self.title = [appDelegate.mReader regionName];
            [self presentViewController: [self makeAlert: @"Success" message:@"Press the power button once. The reader turns on again."] animated:YES completion:nil];
        }
        else if(result == ResultNotSupportFirmware){
            [self presentViewController: [self makeAlert: @"Setting fail" message:@" NOT SUPPORTED REGION"] animated:YES completion:nil];
        }
        else{
            [self presentViewController: [self makeAlert: @"Setting fail" message:@"Please try again"] animated:YES completion:nil];
        }
        
    }];
    
    UIAlertAction *cancel = [UIAlertAction
                             actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action){
        [alert dismissViewControllerAnimated:YES completion:nil];}];
    
    [alert addAction:ok];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _selectedIndex = indexPath.row;
    
    switch (_selectedIndex) {
        case 0 ://US Region
            [self updateRegion:2 regionName:@"US"];
            break;
            
        case 1 ://Au Region
            [self updateRegion:14 regionName:@"Australia"];
            break;
            
        case 2 ://Japan
            [self updateRegion:8 regionName:@"Japan"];
            break;
            
            
        case 3 : //Barzil
            [self updateRegion:5 regionName:@"Brazil"];
            break;
            
        case 4 : //Europe
            [self updateRegion:1 regionName:@"Europe"];
            break;
            
        default:
            break;
            
    }

}


-(UIAlertController*)makeAlert:(NSString*)title message:(NSString *)message{
    
    UIAlertController *alert=   [UIAlertController
                                 alertControllerWithTitle:title
                                 message:message
                                 preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action){
        
        [alert dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [alert addAction:ok];
    
    return alert;
}

@end

