#import "EpcMaskViewController.h"
#import "EpcMaskTableViewCell.h"
#import "EpcMaskEditViewController.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"
#import "SystemSetting.h"
@interface EpcMaskViewController () {
    BOOL isEditCell;
    AppDelegate *appDelegate;
    MBProgressHUD *HUD;
    SystemSetting *systemSetting;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *addBarButtonItem;
@property (weak, nonatomic) IBOutlet UISwitch *matchModeSwitch;
@property (strong, nonatomic) NSMutableArray *maskData;
@end

@implementation EpcMaskViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self enableActionWidgets:NO];
    systemSetting = [SystemSetting sharedSystemSetting];
    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (appDelegate.mReader == nil) {
        [AppDelegate dismissGlobalHUD];
        return;
    }
    
    BOOL matchMode = appDelegate.mReader.epcMaskMatchMode;
    
    [self initLoadMask];
    
    [self.matchModeSwitch setOn:matchMode];
    [AppDelegate dismissGlobalHUD];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(AsReaderGUNDisconnected:) name:@"AsReaderGUNDisconnected" object:nil];
    [center addObserver:self selector:@selector(AsReaderGUNConnected:) name:@"AsReaderGUNConnected" object:nil];
    [appDelegate.mReader setDelegate:self];
    isEditCell = NO;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNDisconnected" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNConnected" object:nil];
} 
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"EpcMaskCell"]) {
        EpcMaskEditViewController *vc = [segue destinationViewController];
        
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        vc.selectMaskParam = [self.maskData objectAtIndex:indexPath.row];
        
        isEditCell = YES;
    }
    
}

#pragma mark - Storyboard Segue
-(IBAction)prepareForUnwind:(UIStoryboardSegue *)segue {
    EpcMaskEditViewController *sourceViewController = segue.sourceViewController;
    
    if (!isEditCell) {
        [self.maskData addObject:sourceViewController.selectMaskParam];
    }
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

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

#pragma mark - UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EpcMaskTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EpcMaskCell" forIndexPath:indexPath];
    
    AsSelectMaskEPCParam *maskParam = [self.maskData objectAtIndex:indexPath.row];
    cell.offsetLabel.text = [NSString stringWithFormat:@"%u bit", maskParam.offset];
    cell.lengthLabel.text = [NSString stringWithFormat:@"%u bit", maskParam.length];
    cell.maskLabel.text = maskParam.mask;
    
    return cell;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.maskData removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];
}

#pragma mark - Getters
- (NSMutableArray *)maskData {
    if (_maskData == nil) {
        _maskData = [[NSMutableArray alloc] init];
    }
    return _maskData;
}

#pragma mark - IBAction
- (IBAction)saveBtnTapped:(id)sender {
    [self enableActionWidgets:NO];
    
    [AppDelegate showGlobalProgressHUDWithTitle:@"Saving..."];
    
    [appDelegate.mReader clearEpcMask];
    
    for (AsSelectMaskEPCParam *mask in self.maskData) {
        [appDelegate.mReader addEpcMask:mask];
    }
    
    if (self.matchModeSwitch.isOn) {
        [appDelegate.mReader setEpcMaskMatchMode:YES];
        [systemSetting setEpcMaskMatchMode:YES];
    } else {
        [appDelegate.mReader setEpcMaskMatchMode:NO];
        [systemSetting setEpcMaskMatchMode:NO];
    }
    
    [systemSetting setSelectionEpcMaskData:self.maskData];
    [self enableActionWidgets:YES];
    
    [AppDelegate dismissGlobalHUD];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Saved successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Custom
- (void)initLoadMask {
    AsSelectMaskEPCParam *param;
    
    int count = [appDelegate.mReader epcMaskCount];
    for (int i=0; i<count; i++) {
        param = [appDelegate.mReader getEpcMask:i];
        if(param !=nil)
        [self.maskData addObject:param];
    }
    
    [self.tableView reloadData];
    
    [self enableActionWidgets:YES];
}
- (void)enableActionWidgets:(BOOL)enabled {
    int count = (int)[self.maskData count];
    
    [self.addBarButtonItem setEnabled:enabled && count < MAX_SELECTION_MASK];
    [self.saveBtn setEnabled:enabled];
    [self.cancelBtn setEnabled:enabled];
    
}

- (BOOL)onAsReaderTriggerKeyEvent:(BOOL)status{
    return NO;
}
- (BOOL)onAsReaderLeftModeKeyEvent:(BOOL)status{
    if(appDelegate.mReader.isRFIDModule&&appDelegate.mReader.isBarcodeModule){
        return YES;
    }
    return NO;
}
- (BOOL)onAsReaderRightModeKeyEvent:(BOOL)status{
    if(appDelegate.mReader.isRFIDModule&&appDelegate.mReader.isBarcodeModule){
        return YES;
    }
    return NO;
}
- (void)updateDeviceState:(ResultCode)error {
    
}
#pragma mark - NSNotification
- (void)AsReaderGUNDisconnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        appDelegate.mReader = nil;
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}

- (void)AsReaderGUNConnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        appDelegate.mReader = [[AsReader alloc] initWithAsReaderGUN:appDelegate.mAsReaderGUN delegate:self];
        [self viewDidAppear:YES];
    });
}
@end
