#import "BarcodeDemoViewController.h"
#import "AsBarcodeItem.h"
#import "BarcodeDemoTableViewCell.h"
#import "UserData.h"
#import "CSVData.h"
#import "SystemSetting.h"
#import "CSVExportTableViewController.h"
#import "Define.h"
#import "ExcelData.h"

#define csvBacodeShow @"csvBarcodeShow"

@interface BarcodeDemoViewController ()
{
    BOOL isScanTimerEnable;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *outputBtn;
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UIView *rescanTimePickerTopView;
@property (weak, nonatomic) IBOutlet UITextField *rescanTimeTextField;
@property (weak, nonatomic) IBOutlet UILabel *totalCountLabel;
@property (strong, nonatomic) IBOutletCollection(UIControl) NSArray *toDisableElems;
@property (strong, nonatomic) NSArray *rescanTimePickerData;
@property (strong, nonatomic) NSArray *rescanTimeData;
@property (readwrite, nonatomic) NSInteger rescanTimeValue;
@property (strong, nonatomic) NSMutableArray *barcodeData;
@property (strong, nonatomic) UIAlertController *actionAlertVC;
@property (assign, nonatomic) NSInteger csvType;
@property (strong, nonatomic) IBOutlet UISegmentedControl *encodingSegment;

@property (weak, nonatomic) IBOutlet UIButton *startScanBtn;
@property (weak, nonatomic) IBOutlet UIButton *stopScanBtn;
@property (weak, nonatomic) IBOutlet UIButton *hwTriggerBtn;




- (IBAction)whenEncodingSegmentChanged:(id)sender;

@end

@implementation BarcodeDemoViewController{
    NSStringEncoding encoding;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    encoding = NSASCIIStringEncoding;
    [self.encodingSegment setSelectedSegmentIndex:0];
    self.rescanTimeTextField.text = [self.rescanTimePickerData objectAtIndex:[[SystemSetting sharedSystemSetting] getBarcodeReScanTime]];
    self.rescanTimeValue = [[SystemSetting sharedSystemSetting] getBarcodeReScanTime];
    if ([[SystemSetting sharedSystemSetting] getBarcodeData]) {
        self.barcodeData = [[NSMutableArray alloc] initWithArray:[[SystemSetting sharedSystemSetting] getBarcodeData]];
    }else{
        self.barcodeData = [[NSMutableArray alloc]init];
    }
    self.totalCountLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.barcodeData.count];
    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.mReader setDelegate:self];
    if (appDelegate.mReader == nil) {
        return;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [appDelegate.mReader setScanMode:BarcodeScanMode];
    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];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    //    appDelegate.mReader.isUseKeyAction = [UserData getIsUseKeyAction];
    
    
    [appDelegate.mReader setBarcodeMode:YES isKeyAction:YES isCustomPreSuffixOn:[[SystemSetting sharedSystemSetting] getCustomPrefixSuffix] type:Temporary];
    
    [AppDelegate dismissGlobalHUD];
    [appDelegate.mReader setScanMode:BarcodeScanMode];
}

- (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 setBarcodeMode:NO isKeyAction:NO isCustomPreSuffixOn:[[SystemSetting sharedSystemSetting] getCustomPrefixSuffix] type:Temporary];
    
}

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

- (UIAlertController *)actionAlertVC {
    if (!_actionAlertVC) {
        _actionAlertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *csvAction = [UIAlertAction actionWithTitle:@"CSV Export" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self csvExport];
        }];
        UIAlertAction *excelAction = [UIAlertAction actionWithTitle:@"Excel Export" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self excelExport];
        }];
        UIAlertAction *excelListAction = [UIAlertAction actionWithTitle:@"Excel List" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
            [self stopScan];
            
            _csvType = 2;
            [self performSegueWithIdentifier:csvBacodeShow sender:nil];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
        
        [_actionAlertVC addAction:csvAction];
        [_actionAlertVC addAction:excelAction];
        [_actionAlertVC addAction:excelListAction];
        [_actionAlertVC addAction:cancelAction];
    }
    return _actionAlertVC;
}

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

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

#pragma mark - UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BarcodeDemoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BarcodeCell" forIndexPath:indexPath];
    
    AsBarcodeItem *item = [self.barcodeData objectAtIndex:indexPath.row];
    
    if (item != nil) {
        cell.codeTypeLabel.text = [AsBarcodeType getBarcodeString:item.barcodeType];
        cell.codeIdLabel.text = item.codeId;
        cell.barcodeLabel.text = item.barcode;
        cell.countLabel.text = [NSString stringWithFormat:@"%d",[item.count intValue]];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AsBarcodeItem *item = [self.barcodeData objectAtIndex:indexPath.row];
    
    if (item != nil) {
        UIAlertView * aleart = [[UIAlertView alloc] initWithTitle:@"" message:
                                [NSString stringWithFormat:@"Code ID :%@\n%@",[AsBarcodeType getBarcodeString:item.barcodeType],item.barcode ]  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
                                                   [aleart show];
    }
    
    
    
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.rescanTimePickerData count];
}

#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [self.rescanTimePickerData objectAtIndex:row];
}

#pragma mark - IBActions
- (IBAction)clearBtnTapped:(id)sender {
    [self.barcodeData removeAllObjects];
    [[SystemSetting sharedSystemSetting] setBarcodeData:self.barcodeData];
    [self.tableView reloadData];
    self.totalCountLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.barcodeData.count];
}

- (IBAction)scanStartBtnTapped:(id)sender {
    [self setScanTimerEnable:YES];
    [self scanEnabled:YES];
}

-(void) stopScan{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startDecoder) object:nil];
    [self setScanTimerEnable:NO];
    [self scanEnabled:NO];
}

- (IBAction)scanStopBtnTapped:(id)sender {

    [self stopScan];
}


-(IBAction)scanHWTriggerStartBtnTapped:(id)sender{
    [self setScanTimerEnable:NO];
    [self scanEnabled:NO];
    UIButton *btn = (UIButton*)sender;
    NSString *btnTitle = [[btn titleLabel] text];
    
    if(!([btnTitle rangeOfString:@"Reset"].location == NSNotFound)){
        [appDelegate.mReader startHWTriggerDecode];
        [btn setTitle:@"Stop Scan" forState:UIControlStateNormal];
    }
    else{
        [appDelegate.mReader stopHWTriggerDecode];
        [btn setTitle:@"Reset Scan" forState:UIControlStateNormal];
    }
}

- (IBAction)rescanTimeBtnTapped:(id)sender {
    self.pickerView.hidden = NO;
    [self.pickerView selectRow:self.rescanTimeValue inComponent:0 animated:NO];
    self.rescanTimePickerTopView.hidden = NO;
}

- (IBAction)pickerCloseBtnTapped:(id)sender {
    [self hidePickerView];
}

- (IBAction)rescanTimePickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    self.rescanTimeTextField.text = [self.rescanTimePickerData objectAtIndex:idx];
    self.rescanTimeValue = idx;
    [[SystemSetting sharedSystemSetting] setBarcodeReScanTime:(int)self.rescanTimeValue];
    [self hidePickerView];
}

- (IBAction)outputCSVBtnTapped:(id)sender {
    [self presentViewController:self.actionAlertVC animated:NO completion:nil];
}

#pragma mark - CSV Export
- (void)csvExport {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.barcodeData && self.barcodeData.count != 0) {
            NSString *timestr = [self currentData];
            NSString *fileName = [NSString stringWithFormat:@"Barcode_%@.csv", timestr];
            //创建csv文件
            [CSVData createCSVWithFileName:fileName export:barcodeExportType];
            [CSVData exportBarCodeCSV:fileName withArray:self.barcodeData export:barcodeExportType];
        }
    });
}



- (void)excelExport {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.barcodeData && self.barcodeData.count != 0) {
            NSString *timestr = [self currentData];
            NSString *fileName = [NSString stringWithFormat:@"Barcode_%@.xlsx", timestr];
            //创建excel文件
            [ExcelData createExcelWithFileName:fileName export:barcodeExportType];
            [ExcelData exportBarcodeExcel:fileName withArray:self.barcodeData export:barcodeExportType];
        }
    });
}

- (NSString *)currentData {
    NSDate *today = [NSDate date];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyyMMddHHmmss"];
    NSString *str = [df stringFromDate:today];
    return str;
}

#pragma mark - Getters
- (NSArray *)rescanTimePickerData {
    return @[@"Not Used", @"100 ms", @"200 ms", @"300 ms", @"400 ms", @"500 ms", @"600 ms", @"700 ms",
             @"800 ms", @"900 ms", @"1000 ms", @"1100 ms", @"1200 ms", @"1300 ms",
             @"1500 ms", @"2000 ms", @"2500 ms", @"3000 ms", @"3500 ms", @"5000 ms",@"10000 ms"];
}

- (NSArray *)rescanTimeData {
    return @[@"0", @"100", @"200", @"300", @"400", @"500",
             @"600", @"700", @"800", @"900", @"1000", @"1100", @"1200", @"1300", @"1500", @"2000", @"2500", @"3000",
             @"3500", @"5000",@"10000"];
}


#pragma mark - Custom
- (void)hidePickerView {
    self.pickerView.hidden = YES;
    self.rescanTimePickerTopView.hidden = YES;
}

-(void)setScanTimerEnable:(BOOL)isEnable{
    isScanTimerEnable = isEnable;
    if(!isEnable)
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startDecoder) object:nil];
}


- (void)scanEnabled:(BOOL)enabled {
    if (enabled) {
        [appDelegate.mReader startDecode];
         [self scanElemEnabled:NO];

    } else {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startDecoder) object:nil];
        [appDelegate.mReader stopSync];
        [self scanElemEnabled:YES];
    }
}


- (void)scanElemEnabled:(BOOL)enabled {
    if (enabled) {
        for (UIControl *control in self.toDisableElems) {
            [control setEnabled:YES];
        }
        self.outputBtn.enabled = YES;
    } else {
        
        for (UIControl *control in self.toDisableElems) {
            [control setEnabled:NO];
        }
        self.outputBtn.enabled = YES;
    }
}

#pragma mark - Reader Event Handler Methods
- (BOOL)onAsReaderTriggerKeyEvent:(BOOL)status{
    [self setScanTimerEnable:status];
    if(status){
        [self scanEnabled:YES];
        
    }else{
        [self scanEnabled:NO];
    }
    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 {
    if((action == CommandStop)&&isScanTimerEnable) {
        int rescanTime = [[self.rescanTimeData objectAtIndex:self.rescanTimeValue] intValue];
        if (rescanTime > 0) {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startDecoder) object:nil];
            [self performSelector:@selector(startDecoder) withObject:nil afterDelay:rescanTime / 1000.00];
        } else {
            [self scanElemEnabled:YES];
        }
    }
}


-(void)startDecoder{
    [self scanEnabled:YES];
}


- (void)detectBarcode:(BarcodeType)barcodeType codeId:(NSString *)codeId barcodeData:(NSData *)barcodeData{
    
    
        [_hwTriggerBtn setTitle:@"Reset Scan" forState:UIControlStateNormal];
 
    
    NSString * barcode = [[NSString alloc] initWithData:barcodeData encoding:encoding];
    if (!barcode) {
        barcode = [[NSString alloc] initWithData:barcodeData encoding:NSASCIIStringEncoding];
    }
    //if (barcodeType != BarcodeTypeNoRead) {
    
    //Check old Data
    BOOL isNew = YES;
    for (int i=0; i<self.barcodeData.count; i++) {
        AsBarcodeItem *item = [self.barcodeData objectAtIndex:i];
        if(([item.barcode isEqualToString:barcode])&&
           ([item.codeId isEqualToString:codeId])){
            //replace Barcde data
            isNew = NO;
            item.count  =  [NSString stringWithFormat:@"%d",[item.count intValue]+1];
            [self.barcodeData replaceObjectAtIndex:i withObject:item];
            break;
        }
    }
    
    if(isNew){
        AsBarcodeItem *item = [[AsBarcodeItem alloc] init];
        item.barcodeType = barcodeType;
        item.codeId = codeId;
        item.barcode = barcode;
        item.count  = @"1";
        NSDate *timeDate = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"YYYY/MM/dd HH:mm:ss"];
        NSString *dateTime = [formatter stringFromDate:timeDate];
        item.dateTime = dateTime;
        [self.barcodeData addObject:item];
    }
    
    [[SystemSetting sharedSystemSetting] setBarcodeData:self.barcodeData];
    
    [self.tableView reloadData];
    
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.barcodeData.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    self.totalCountLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.barcodeData.count];
    // }
}

//- (void)detectBarcode:(BarcodeType)barcodeType codeId:(NSString *)codeId barcodeData:(NSData *)barcodeData{
//}

- (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;
        [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];
    });
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:csvBacodeShow]) {
        CSVExportTableViewController *exportVC = segue.destinationViewController;
        if (1 == _csvType) {
            exportVC.typeStr = @"csvBarcode";
        } else {
            exportVC.typeStr = @"excelBarcode";
        }
    }
}

- (IBAction)whenEncodingSegmentChanged:(id)sender {
    UISegmentedControl* control = (UISegmentedControl*)sender;
    switch (control.selectedSegmentIndex) {
        case 0:
            encoding = NSASCIIStringEncoding;
            break;
        case 1:
            encoding = NSUTF8StringEncoding;
            break;
        case 2:
            encoding = NSShiftJISStringEncoding;
            break;
        default:
            encoding = NSASCIIStringEncoding;
            break;
    }
}
@end
