#import "BarcodeOptionViewController.h"
#import "BarcodeOption_VC.h"
#import "SystemSetting.h"

typedef enum {
    ParamDataTypeLocal = 0, // 'App Memory'
    ParamDataTypeModule = 1,// 'Barcode Module '
    ParamDataTypeBoth = 2   //APP & Module
} ParamDataType;


@interface BarcodeOptionViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *barcodeParamData;
@property (weak, nonatomic) IBOutlet UISwitch *customPrefixSuffixSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *saveTypeSwitch;
@end

@implementation BarcodeOptionViewController{
    SystemSetting * systemSetting;
}


- (IBAction)defaultPrefixSuffixSwitchAction:(id)sender {
    //OFF : Default preffix  ON : User Preffix
    [systemSetting setCustomPrefixSuffix:_customPrefixSuffixSwitch.isOn];
    [appDelegate.mReader setBarcodeMode:YES isKeyAction:YES isCustomPreSuffixOn:_customPrefixSuffixSwitch.isOn type:Temporary];
    
    if(_customPrefixSuffixSwitch.isOn)
        [self showAlertTitle:@"Enable" Message:@"Set prefix/suffix following the barcode setting manual."];
    else
        [self showAlertTitle:@"Disable" Message:@"Custom prefix/suffix setting is unnecessary."];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.mReader setDelegate:self];
    
    systemSetting = [SystemSetting sharedSystemSetting];
    if (appDelegate.mReader == nil) {
        return;
    }else{
        if (!appDelegate.mReader.isRFIDModule) {
            UIBarButtonItem * rightItem =[[UIBarButtonItem alloc]initWithTitle:@"Setting" style:UIBarButtonItemStyleDone target:self action:@selector(setting)];
            self.navigationItem.rightBarButtonItem = rightItem;
        }
    }
}
- (void)setting{
    BarcodeOption_VC * barcodeViewController=  (BarcodeOption_VC *)[self.storyboard instantiateViewControllerWithIdentifier:@"BarcodeOption_VC"];
    [self.navigationController pushViewController:barcodeViewController animated:YES];
}

- (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];
    [appDelegate.mReader setScanMode:BarcodeScanMode];
}


-(void)viewDidAppear:(BOOL)animated{
    [appDelegate.mReader setPropBarcodeMode:YES];
    
    //Is temporary ?
    if([systemSetting getBarcodeSettingSaveTypeIsTemporary]){
        //Temporary
        [self updateSymbologyTable:ParamDataTypeLocal];
        [AppDelegate dismissGlobalHUD];
        [self saveSymbology:ParamDataTypeModule message:@"-Get Symbology from app memory"];
        
        if(self.barcodeParamData.count == 0){
            [self updateSymbologyTable:ParamDataTypeModule];
        }
      
    }else{
        //permanent
        [self updateSymbologyTable:ParamDataTypeModule];
    }
    
   
    [_saveTypeSwitch setOn:[systemSetting getBarcodeSettingSaveTypeIsTemporary]];
    
    if([systemSetting getCustomPrefixSuffix]){
        [_customPrefixSuffixSwitch setOn:YES];
        [appDelegate.mReader setBarcodeMode:YES isKeyAction:YES isCustomPreSuffixOn:_customPrefixSuffixSwitch.isOn type:Temporary];
        
    }else{
        [_customPrefixSuffixSwitch setOn:NO];
        [appDelegate.mReader setBarcodeMode:YES isKeyAction:YES isCustomPreSuffixOn:_customPrefixSuffixSwitch.isOn type:Temporary];
    }

    [AppDelegate dismissGlobalHUD];
}

- (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 setScanMode:RFIDScanMode];
    [appDelegate.mReader setBarcodeMode:NO isKeyAction:NO isCustomPreSuffixOn:[systemSetting getCustomPrefixSuffix] type:Temporary];
}

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

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

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

#pragma mark - UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BarcodeCell" forIndexPath:indexPath];
    
    AsParamValue *paramValue = [self.barcodeParamData objectAtIndex:indexPath.row];
//    cell.textLabel.text = [AsParamName msg:paramValue.paramName];
    cell.textLabel.text = [AsParamName getName:paramValue.paramName];

    if (paramValue.value) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    AsParamValue *paramValue = [self.barcodeParamData objectAtIndex:indexPath.row];
    
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        paramValue.value = 0;
    } else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        paramValue.value = 1;
    }
}

- (IBAction)defaultAllSymBtnTapped:(id)sender {
   for (AsParamValue *paramValue in self.barcodeParamData) {
          switch(paramValue.paramName) {
              case Codabar:
                  [paramValue setEnabled:YES];
                  break;
              case Code39:
                  [paramValue setEnabled:YES];
                  break;
              case Code32Pharmaceutical:
                  [paramValue setEnabled:NO];
                  break;
              case I2of5:
                  [paramValue setEnabled:YES];
                  break;
              case NEC2of5:
                  [paramValue setEnabled:YES];
                  break;
              case Code93:
                  [paramValue setEnabled:YES];
                  break;
              case R2of5:
                  [paramValue setEnabled:NO];
                  break;
              case A2of5:
                  [paramValue setEnabled:NO];
                  break;
              case X2of5:
                  [paramValue setEnabled:NO];
                  break;
              case Code11:
                  [paramValue setEnabled:NO];
                  break;
              case Code128:
                  [paramValue setEnabled:YES];
                  break;
              case GS1128:
                  [paramValue setEnabled:YES];
                  break;
              case Telepen:
                  [paramValue setEnabled:NO];
                  break;
              case UPCA:
                  [paramValue setEnabled:YES];
                  break;
              case UPCACouponCode:
                  [paramValue setEnabled:NO];
                  break;
              case CouponGS1DataBarOutput:
                  [paramValue setEnabled:NO];
                  break;
              case UPCE0:
                  [paramValue setEnabled:YES];
                  break;
              case UPCE1:
                  [paramValue setEnabled:NO];
                  break;
              case EAN13:
                  [paramValue setEnabled:YES];
                  break;
              case EAN8:
                  [paramValue setEnabled:YES];
                  break;
              case MSI:
                  [paramValue setEnabled:NO];
                  break;
              case RSS14:
                  [paramValue setEnabled:YES];
                  break;
              case RSSLimit:
                  [paramValue setEnabled:YES];
                  break;
              case RSSExp:
                  [paramValue setEnabled:YES];
                  break;
              case TriopticCode:
                  [paramValue setEnabled:NO];
                  break;
              case CodablockA:
                  [paramValue setEnabled:NO];
                  break;
              case CodablockF:
                  [paramValue setEnabled:NO];
                  break;
              case PDF417:
                  [paramValue setEnabled:YES];
                  break;
              case MacroPDF417:
                  [paramValue setEnabled:YES];
                  break;
              case MicroPDF:
                  [paramValue setEnabled:NO];
                  break;
              case ComCode:
                  [paramValue setEnabled:NO];
                  break;
              case GS1Emulation:
                  [paramValue setEnabled:NO];
                  break;
              case TLC39:
                  [paramValue setEnabled:NO];
                  break;
              case QRCode:
                  [paramValue setEnabled:YES];
                  break;
              case Matrix:
                  [paramValue setEnabled:YES];
                  break;
              case MaxiCode:
                  [paramValue setEnabled:NO];
                  break;
              case AztecCode:
                  [paramValue setEnabled:YES];
                  break;
              case HanXinCode:
                  [paramValue setEnabled:NO];
                  break;
              case PostalCodes:
                  [paramValue setEnabled:NO];
                  break;
              case ChinaPost:
                  [paramValue setEnabled:NO];
                  break;
              case KoreaPost:
                  [paramValue setEnabled:NO];
                  break;
              
              default:
                  break;
          }
          
      }
      [self.tableView reloadData];
}



- (IBAction)barcodeSaveTypeSwitch:(id)sender {
    [systemSetting setBarcodeSettingSaveType:_saveTypeSwitch.isOn];
    
    if(_saveTypeSwitch.isOn){
        //Temporary
        //3-1 : Switch (Permanent -> Temporary)
        //3-2 : Get Symbology from app memory
        //3-3 : Symbology data display and save to barcode module
        [self updateSymbologyTable:ParamDataTypeLocal];
        [self saveSymbology:ParamDataTypeModule message:@"-Get Symbology from app memory"];
    }else{
        //Permanent
        //3-4 : Switch (Temporary -> Permanent)
        //3-5 : Get Symbology from barcode module
        //3-6 : Symbology data display and save to app memory
        [self updateSymbologyTable:ParamDataTypeModule];
        [self saveSymbology:ParamDataTypeLocal message:@"-Get Symbology from barcode module"];
    }
    NSLog(@" Barcode type Switch Event  :%d",_saveTypeSwitch.isOn);
    
}


- (IBAction)disableAllSymBtnTapped:(id)sender {
    for (AsParamValue *paramValue in self.barcodeParamData) {
        [paramValue setEnabled:NO];
    }
    [self.tableView reloadData];
}

- (IBAction)enableAllSymBtnTapped:(id)sender {
    for (AsParamValue *paramValue in self.barcodeParamData) {
        [paramValue setEnabled:YES];
    }
    [self.tableView reloadData];
}

- (IBAction)saveSymBtnTapped:(id)sender {
//    ResultCode res = [appDelegate.mReader setBarcodeParam:self.barcodeParamData];
    [self saveSymbology:ParamDataTypeBoth message:@""];

}

-(void)showAlertTitle:(NSString*)title Message:(NSString*)message{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    
}




#pragma mark - Reader Event Handler Methods
- (BOOL)onAsReaderTriggerKeyEvent:(BOOL)status{
//    [appDelegate.mReader setSacnModel:BarcodeScanModel];
    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 {
    if (error != ResultNoError) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Failed to get response. Try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

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

- (void)changedActionState:(CommandType)action resultCode:(NSInteger)resultCode {
    
}
 
- (void)accessResult:(ResultCode)error actionState:(CommandType)action epc:(NSString *)epc data:(NSString *)data rssi:(float)rssi phase:(float)phase frequency:(float)frequency {
}

#pragma mark - NSNotification
- (void)AsReaderGUNDisconnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        appDelegate.mReader = nil;
        [AppDelegate dismissGlobalHUD];
        [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];
    });
}


#pragma mark - SymbologControl

- (void)saveSymbology:(ParamDataType)paramDataType message:(NSString*)message{
//    ResultCode res = [appDelegate.mReader setBarcodeParam:self.barcodeParamData];
    ResultCode res = ResultNoError;
    [AppDelegate showGlobalProgressHUDWithTitle:@"Saving..."];
    NSMutableString *alertMessage = [[NSMutableString alloc]initWithString:message];
    ParamType saveType = Permanent;
    
    //Temporary on
    if([systemSetting getBarcodeSettingSaveTypeIsTemporary]){
        saveType = Temporary;
        [alertMessage appendString:@"\n-Save Type : Temporary"];
    }
    else{
        [alertMessage appendString:@"\n-Save Type : Permanent"];
    }
        
        
    if(paramDataType == ParamDataTypeLocal){
        [systemSetting setBarcodeParamData:self.barcodeParamData];
        [alertMessage appendString:@"\n-Save to APP Memory"];
    }
    
    if(paramDataType == ParamDataTypeModule){
        [alertMessage appendString:@"\n-Save to barcode module"];
        for (AsParamValue *paramName in self.barcodeParamData) {
            res = [appDelegate.mReader setBarcodeParam:paramName type:saveType];
            if (res != ResultNoError) {
                [AppDelegate dismissGlobalHUD];
                return;
            }
        }
    }
    
    if(paramDataType == ParamDataTypeBoth){
        [alertMessage appendString:@"\n-Save to barcode module + App Memory"];
        [systemSetting setBarcodeParamData:self.barcodeParamData];
        for (AsParamValue *paramName in self.barcodeParamData) {
            res = [appDelegate.mReader setBarcodeParam:paramName type:saveType];
            if (res != ResultNoError) {
                [AppDelegate dismissGlobalHUD];
                return;
            }
        }
    }
    
    [AppDelegate dismissGlobalHUD];
    if (res == ResultNoError) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Saved successfully" message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to save" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }

}


- (void)updateSymbologyTable:(ParamDataType)paraDataType{
    NSArray *paramData = [[NSArray alloc] initWithObjects:
                          [NSNumber numberWithInt:Codabar],
                          [NSNumber numberWithInt:Code39],
                          [NSNumber numberWithInt:Code32Pharmaceutical],
                          [NSNumber numberWithInt:I2of5],
                          [NSNumber numberWithInt:NEC2of5],
                          [NSNumber numberWithInt:Code93],
                          [NSNumber numberWithInt:R2of5],
                          [NSNumber numberWithInt:A2of5],
                          [NSNumber numberWithInt:X2of5],
                          [NSNumber numberWithInt:Code11],
                          [NSNumber numberWithInt:Code128],
                          [NSNumber numberWithInt:GS1128],
                          [NSNumber numberWithInt:Telepen],
                          [NSNumber numberWithInt:UPCA],
                          [NSNumber numberWithInt:UPCACouponCode],
                          [NSNumber numberWithInt:CouponGS1DataBarOutput],
                          [NSNumber numberWithInt:UPCE0],
                          [NSNumber numberWithInt:UPCE1],
                          [NSNumber numberWithInt:EAN13],
                          [NSNumber numberWithInt:EAN8],
                          [NSNumber numberWithInt:MSI],
                          [NSNumber numberWithInt:RSS14],
                          [NSNumber numberWithInt:RSSLimit],
                          [NSNumber numberWithInt:RSSExp],
                          [NSNumber numberWithInt:TriopticCode],
                          [NSNumber numberWithInt:CodablockA],
                          [NSNumber numberWithInt:CodablockF],
                          [NSNumber numberWithInt:PDF417],
                          [NSNumber numberWithInt:MacroPDF417],
                          [NSNumber numberWithInt:MicroPDF],
                          [NSNumber numberWithInt:ComCode],
                          [NSNumber numberWithInt:GS1Emulation],
                          [NSNumber numberWithInt:TLC39],
                          [NSNumber numberWithInt:QRCode],
                          [NSNumber numberWithInt:Matrix],
                          [NSNumber numberWithInt:MaxiCode],
                          [NSNumber numberWithInt:AztecCode],
                          [NSNumber numberWithInt:HanXinCode],
                          [NSNumber numberWithInt:PostalCodes],
                          [NSNumber numberWithInt:ChinaPost],
                          [NSNumber numberWithInt:KoreaPost],
                          nil];
    
    NSMutableArray *arrParam = [[NSMutableArray alloc] init];
    
    
    //APP MemoryData
    if(paraDataType == ParamDataTypeLocal){
        if ([systemSetting getBarcodeParamData] && [[systemSetting getBarcodeParamData] count] > 0 ) {
            self.barcodeParamData = (NSArray *)[systemSetting getBarcodeParamData];
        }else{
            
        }
    }
    //Reader Data
    else{
        for (NSNumber *paramName in paramData) {
            AsParamValue * val = [appDelegate.mReader getBarcodeParam:paramName];
            if(val != nil)
            {
                [arrParam addObject:val];
            }
        }
        self.barcodeParamData = (NSArray *)arrParam;
    }
    [self.tableView reloadData];
}



@end
