#define PICKER_VIEW_INVENTORY_SESSION   0
#define PICKER_VIEW_SESSION_FLAG        1
#define PICKER_VIEW_SELECT_FLAG         2

#import "SelectionMaskViewController.h"
#import "SelectionMaskEditViewController.h"
#import "SelectionMaskTableViewCell.h"
#import "AppDelegate.h"
#import "SystemSetting.h"
#import <AsReaderGunSDK/AsReaderGunSDK.h>

@interface SelectionMaskViewController ()
{
    BOOL isEditCell;
    SystemSetting * systemSetting;
}
@property (strong, nonatomic) NSArray *selectFlagPickerData;
@property (strong, nonatomic) NSArray *inventorySessionPickerData;
@property (strong, nonatomic) NSArray *sessionFlagPickerData;
@property (strong, nonatomic) NSMutableArray *maskData;
@property (readwrite, nonatomic) SelectFlag selectFlag;
@property (readwrite, nonatomic) SessionType inventorySession;
@property (readwrite, nonatomic) SessionFlag sessionFlag;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *selectFlagTextField;
@property (weak, nonatomic) IBOutlet UITextField *inventorySessionTextField;
@property (weak, nonatomic) IBOutlet UITextField *sessionFlagTextField;
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIView *selectFlagPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *inventorySessionPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *sessionFlagPickerTopView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *addBarButtonItem;

@end

@implementation SelectionMaskViewController
@synthesize selectFlag = _selectFlag;

- (void)viewDidLoad {
    [super viewDidLoad];
    systemSetting = [SystemSetting sharedSystemSetting];
    [self enableActionWidgets:NO];
    
    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (appDelegate.mReader == nil) {
        [AppDelegate dismissGlobalHUD];
        return;
    }
    [self initLoadMask];
    
    [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];
    [appDelegate.mReader setDelegate:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"SelectionMaskCell"]) {
        SelectionMaskEditViewController *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 {
    SelectionMaskEditViewController *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 {
    SelectionMaskTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelectionMaskCell" forIndexPath:indexPath];
    
    AsSelectMaskParam *maskParam = [self.maskData objectAtIndex:indexPath.row];
    cell.targetLabel.text = [DATA_TARGET objectAtIndex:maskParam.target];
    cell.actionLabel.text = [AsMaskActionType toString:maskParam.action targetType:maskParam.target];
    cell.bankLabel.text = [DATA_BANK objectAtIndex:maskParam.bank];
    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 - UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView.tag == PICKER_VIEW_SELECT_FLAG) {
        return self.selectFlagPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_INVENTORY_SESSION) {
        return self.inventorySessionPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_SESSION_FLAG) {
        return self.sessionFlagPickerData.count;
    }
    return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView.tag == PICKER_VIEW_SELECT_FLAG) {
        return [self.selectFlagPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_INVENTORY_SESSION) {
        return [self.inventorySessionPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_SESSION_FLAG) {
        return [self.sessionFlagPickerData objectAtIndex:row];
    }
    return @"None";
}

#pragma mark - IBAction
- (IBAction)saveBtnTapped:(id)sender {
    [self enableActionWidgets:NO];
    [AppDelegate showGlobalProgressHUDWithTitle:@"Saving..."];
    AsSelectMaskParam *param;
    for (int i=MIN_SELECTION_MASK; i < MAX_SELECTION_MASK; i++) {
        if (i < self.maskData.count) {
            param = [self.maskData objectAtIndex:i];
            [appDelegate.mReader setSelectionMask:i withParam:param];
        } else {
            [appDelegate.mReader removeSelectionMask:i];
        }
    }
    
    if ([self.maskData count] > 0) {
        [appDelegate.mReader setUseSelectionMask:self.selectFlag + 1];
        [systemSetting setUseSelectionMask:self.selectFlag + 1];
    }else {
        [appDelegate.mReader clearSelectionMask];
    }
    
    [appDelegate.mReader setInventorySession:self.inventorySession];
    [appDelegate.mReader setSessionFlag:self.sessionFlag];
    
    [systemSetting setInventorySession:self.inventorySession];
    [systemSetting setSessionFlag:self.sessionFlag];
    [systemSetting setEpcMaskData: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];
}

- (IBAction)selectFlagBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_SELECT_FLAG;
    [self.pickerView reloadAllComponents];
    
    [self.pickerView selectRow:self.selectFlag inComponent:0 animated:NO];
    
    self.pickerView.hidden = NO;
    self.selectFlagPickerTopView.hidden = NO;
}

- (IBAction)inventorySessionBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_INVENTORY_SESSION;
    [self.pickerView reloadAllComponents];
    
    [self.pickerView selectRow:self.inventorySession inComponent:0 animated:NO];
    
    self.pickerView.hidden = NO;
    self.inventorySessionPickerTopView.hidden = NO;
}

- (IBAction)sessionFlagBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_SESSION_FLAG;
    [self.pickerView reloadAllComponents];
    
    [self.pickerView selectRow:self.sessionFlag inComponent:0 animated:NO];
    
    self.pickerView.hidden = NO;
    self.sessionFlagPickerTopView.hidden = NO;
}

- (IBAction)selectFlagPickerOkBtnTapped:(id)sender {
    [self setSelectFlag:(int)[self.pickerView selectedRowInComponent:0]];
    
    [self hidePickerView];
}

- (IBAction)inventorySessionPickerOkBtnTapped:(id)sender {
    [self setInventorySession:(int)[self.pickerView selectedRowInComponent:0]];
    
    [self hidePickerView];
}

- (IBAction)sessionFlagPickerOkBtnTapped:(id)sender {
    [self setSessionFlag:(int)[self.pickerView selectedRowInComponent:0]];
    
    [self hidePickerView];
}
- (IBAction)pickerCloseBtnTapped:(id)sender {
    [self hidePickerView];
}

#pragma mark - Getters
- (NSArray *)selectFlagPickerData {
    return DATA_SELECT_FLAG;
}
- (NSArray *)inventorySessionPickerData {
    return DATA_INVENTORY_SESSION;
}
- (NSArray *)sessionFlagPickerData {
    return DATA_SESSION_FLAG;
    
}
- (NSMutableArray *)maskData {
    if (_maskData == nil) {
        _maskData = [[NSMutableArray alloc] init];
    }
    return _maskData;
}

- (SelectFlag)selectFlag {
    return _selectFlag;
}

#pragma mark - Setters
- (void)setSelectFlag:(SelectFlag)selectFlag {
    self.selectFlagTextField.text = [self.selectFlagPickerData objectAtIndex:selectFlag];
    _selectFlag = selectFlag;
}

- (void)setInventorySession:(SessionType)inventorySession {
    self.inventorySessionTextField.text = [self.inventorySessionPickerData objectAtIndex:inventorySession];
    _inventorySession = inventorySession;
}

- (void)setSessionFlag:(SessionFlag)sessionFlag {
    self.sessionFlagTextField.text = [self.sessionFlagPickerData objectAtIndex:sessionFlag];
    _sessionFlag = sessionFlag;
}

#pragma mark - Custom
- (void)initLoadMask {
    AsSelectMaskParam *param;
    for (int i=MIN_SELECTION_MASK; i<MAX_SELECTION_MASK; i++) {
        if (![appDelegate.mReader usedSelectionMask:i]) {
            break;
        }
        param = [appDelegate.mReader getSelectionMask:i];
        [self.maskData addObject:param];
    }
    
    [self.tableView reloadData];
    
    SelectFlag selectFlag = [appDelegate.mReader useSelectionMask];
    
    if (selectFlag == SelectFlag_NotUsed)
        selectFlag = SelectFlag_SL;
    
    self.selectFlag = selectFlag - 1;
    
    [self setInventorySession:appDelegate.mReader.inventorySession];
    
    [self setSessionFlag:appDelegate.mReader.sessionFlag];
    
    [self enableActionWidgets:YES];
}

- (void)hidePickerView {
    self.pickerView.hidden = YES;
    self.selectFlagPickerTopView.hidden = YES;
    self.inventorySessionPickerTopView.hidden = YES;
    self.sessionFlagPickerTopView.hidden = 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];
    
}

#pragma mark - Reader Event Handler Methods
- (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 {
    
}

- (void)readTag:(NSString *)tag rssi:(float)rssi phase:(float)phase {
    
}

- (void)changedActionState:(CommandType)action resultCode:(NSInteger)resultCode {
    
} 

#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
