//
//  InventoryScanViewController.m
//  AT188N_DEMO_1703
//
//  Created by 류은주 on 2017. 4. 20..
//  Copyright © 2017년 ATID. All rights reserved.
//
#define ALERT_VIEW_SELECTION_MASK    0


#import "InventoryScanViewController.h"
#import "SWRevealViewController.h"
#import "InventoryTableViewCell.h"
#import "EATagItem.h"
#import "RFIDOptionViewController.h"


@interface InventoryScanViewController ()
{
    BOOL _isReloadNeeded;

    int isScanning;
    int selectedcell;
    
    BOOL inventorymode;
    
    BOOL inventoryView;

    BOOL nomoduleflag;
    
    int inventoryformat;

}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *menuopen;
@property (weak, nonatomic) IBOutlet UILabel *tagCountLabel;
@property (weak, nonatomic) IBOutlet UIButton *inventoryBtn;
@property (strong, nonatomic) IBOutletCollection(UIControl) NSArray *toDisableElems;
@property (readwrite, nonatomic) NSInteger tagtype;

@end

@implementation InventoryScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    SWRevealViewController *revealController = self.revealViewController;
    
    if(revealController)
    {
        [self.menuopen setTarget:self.revealViewController];
        [self.menuopen setAction:@selector(revealToggle:)];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
        //    [revealController panGestureRecognizer];
            [revealController tapGestureRecognizer];
        //    open = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:revealController action:@selector(revealToggle:)];
    }
    [self.inventoryBtn setEnabled:NO];
    for (UIControl *control in self.toDisableElems) {
        [control setEnabled:NO];
    }
    _isReloadNeeded = YES;
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.mReader setDelegate:self];
    
    nomoduleflag = 0;
    
//    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
    
    
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        // Do something...
       
        aryTags = [[NSMutableArray alloc] init];
        mapTags = [[NSMutableDictionary alloc] init];
        
        mTotalTagCount = 0;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            [appDelegate.mReader setDelegate:self];
            _deviceInfo = [[DeviceSelectInfoDB alloc] init];
            [_deviceInfo SaveBTInfo:appDelegate.connectdevicename macaddress:appDelegate.connectdeviceadd];
            if (appDelegate.mReader == nil) {
                return;
            }
            inventoryformat = appDelegate.mReader.inventoryFormat;
            [self.tableView reloadData];
            [AppDelegate dismissGlobalHUD];
        });
        
    });
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
   
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(BluetoothDisconnected:) name:@"BluetoothDisconnected" object:nil];
    
    [appDelegate.mReader setDelegate:self];
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    HUD.labelText = @"Loading...";
    [HUD show:YES];
    [self.navigationController.view addSubview:HUD];
    
    if (_isReloadNeeded == NO) {
        return;
    }

    _isReloadNeeded = YES;
    
    inventoryView = 1;

    nomoduleflag = 1;
    
    
    
    if(inventoryformat != appDelegate.mReader.inventoryFormat){
        [self clearView];
    }
}
- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    appDelegate.mReader.singleMulti = appDelegate.inventorymode;
    NSLog(@"inventoryformat  %d  appDelegate.inventorymode %d",inventoryformat,appDelegate.inventorymode);

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [HUD hide:YES];
        [HUD removeFromSuperview];
        [self.inventoryBtn setEnabled:YES];
        for (UIControl *control in self.toDisableElems) {
            [control setEnabled:YES];
        }
        [self buttonstate];
    });

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

    [appDelegate.mReader stop];
    appDelegate.inventorymode = appDelegate.mReader.singleMulti;
    [HUD hide:YES];
    [HUD removeFromSuperview];
    [self.inventoryBtn setEnabled:NO];
    for (UIControl *control in self.toDisableElems) {
        [control setEnabled:NO];
    }

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"RFIDOption"]) {
        RFIDOptionViewController *vc = [segue destinationViewController];
        vc.inventoryview = inventoryView;
        
        inventoryformat = appDelegate.mReader.inventoryFormat;
        NSLog(@"InventoryScanViewController  prepareForSegue %d",inventoryformat);
    }
}
#pragma mark - Storyboard Segue
-(IBAction)prepareForUnwind:(UIStoryboardSegue *)segue {
    NSLog(@"%s", __func__);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.

        return aryTags.count;
}

#pragma mark - UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    InventoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InventoryCell" forIndexPath:indexPath];
        // Configure the cell...
        EATagItem *item = nil;
        
        item = [aryTags objectAtIndex:indexPath.row];
        if (item != nil) {
            cell.Tagvalue.text = item.tag;
            NSLog(@"tag string [%@]",item.tag);
            cell.tagcnt.text = [NSString stringWithFormat:@"%d", item.count];
            cell.SerialLabel.text = item.extradata;
        }
    
    return cell;
}

- (void)scanElemEnabled:(BOOL)enabled {
    if (enabled) {
        isScanning = NO;
        
        [self.inventoryBtn setTitle:@"Start" forState:UIControlStateNormal];
        
        for (UIControl *control in self.toDisableElems) {
            [control setEnabled:YES];
        }
    } else {
        isScanning = YES;
        
        [self.inventoryBtn setTitle:@"Stop" forState:UIControlStateNormal];
        
        for (UIControl *control in self.toDisableElems) {
            [control setEnabled:NO];
        }
    }
}

- (IBAction)inventoryBtnTapped:(id)sender {
  
        // 스캔 버튼이 눌렸을 경우
        if ([appDelegate.mReader getAction] == CommandStop) {
            inventorymode = 1;
//            [appDelegate.mReader stopflagoff];
            [appDelegate.mReader inventory:appDelegate.maskstrvalue];
        } else {
            // 스캔 중인 경우 중지
            [appDelegate.mReader stop];
//            [appDelegate.mReader stopflagon];
        }
}
- (IBAction)clearBtnTapped:(id)sender {

 /*       [aryTags removeAllObjects];
        [mapTags removeAllObjects];
        mTotalTagCount = 0;
    
        [self.tagCountLabel setText:[NSString stringWithFormat:@"%d / %ld", (int)aryTags.count , mTotalTagCount]];
//        [self.totalTagCountLabel setText:[NSString stringWithFormat:@"%d", (int)aryTags.count]];
    
        mLastTime = 0;
    

    [self.tableView reloadData];*/
    
    [self clearView];
}

- (void) clearView {
    [aryTags removeAllObjects];
    [mapTags removeAllObjects];
    mTotalTagCount = 0;
    
    [self.tagCountLabel setText:[NSString stringWithFormat:@"%d / %ld", (int)aryTags.count , mTotalTagCount]];
    //        [self.totalTagCountLabel setText:[NSString stringWithFormat:@"%d", (int)aryTags.count]];
    
    mLastTime = 0;
    
    
    [self.tableView reloadData];
}

#pragma mark - Reader Event Handler Methods
- (void)deviceStateChange:(ResultType)error {
    if (error != ResultNoError) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"Failed to get response. Try again." preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* ok = [UIAlertAction
                             actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                             }];
        
        [alert addAction:ok];
        
        
        //        [self presentViewController:alert animated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)readTagResult:(NSString *)tag extradata:(NSString *)extradata {
    mTotalTagCount++;
    
    
    EATagItem *item = nil;
    if ((item = (EATagItem *)[mapTags objectForKey:tag]) != nil) {
        item.count++;

    } else {
        item = [EATagItem itemWith:tag extradata:extradata];
        [aryTags addObject:item];
        [mapTags setObject:item forKey:tag];
    }
    
//    NSLog(@"readTagResult %@  aryTags.count %d mTotalTagCount %ld",item.tag,(int)aryTags.count,mTotalTagCount);
    
    [self.tagCountLabel setText:[NSString stringWithFormat:@"%d / %ld", (int)aryTags.count, mTotalTagCount]];

    [self.tableView reloadData];
    
}

- (void)changedActionState:(CommandType)action {
    NSLog(@"Action : %02X", action);
    [self buttonstate];
    
}

- (void) buttonstate {
    // 스캔 버튼이 눌렸을 경우
    if ([appDelegate.mReader getAction] != CommandStop) {
        [self.inventoryBtn setTitle:@"Stop" forState:UIControlStateNormal];
        
//        for (UIControl *control in self.toDisableElems) {
//            [control setEnabled:NO];
//        }
        [self scanElemEnabled:NO];
        [self.menuopen setEnabled:NO];
        [self.view removeGestureRecognizer:self.revealViewController.panGestureRecognizer];
    }  else {
        // 스캔 중인 경우 중지
        [self.inventoryBtn setTitle:@"Start" forState:UIControlStateNormal];
        
//        for (UIControl *control in self.toDisableElems) {
//            [control setEnabled:YES];
//        }
        [self scanElemEnabled:YES];
        [self.menuopen setEnabled:YES];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
        inventorymode = 0;
    }
}

#pragma mark - NSNotification
-(void)BluetoothDisconnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self performSegueWithIdentifier:@"RegistDevice" sender:nil];
    });
}
@end

