//
//  StoredDataViewController.m
//  AT188N_DEMO_1703
//
//  Created by 류은주 on 2017. 3. 28..
//  Copyright © 2017년 ATID. All rights reserved.
//

#import "StoredDataViewController.h"
#import "SWRevealViewController.h"
#import "StoredDataTableViewCell.h"
#import "EATagItem.h"

@interface StoredDataViewController () {
    NSInteger storedCount;
//    MBProgressHUD * hudProgress;
    BOOL isload;
}

@property (strong, nonatomic) NSMutableArray *storedData;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *menuopen;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *totalCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalDataCountLabel;
@property (weak, nonatomic) IBOutlet UITextField *storedcountTextField;
@property (weak, nonatomic) IBOutlet UIButton *removeBtn;
@property (weak, nonatomic) IBOutlet UIButton *loadBtn;
@property (weak, nonatomic) IBOutlet UIButton *clearBtn;

@end

@implementation StoredDataViewController

- (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];
    }
    isload = 0;
    storedCount = 0;
//    hudProgress = nil;
    [self.storedcountTextField setAllowsEditingTextAttributes:NO];

    self.storedcountTextField.userInteractionEnabled = NO;
    
//    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    HUD.labelText = @"Loading...";
    [self.navigationController.view addSubview:HUD];
    [HUD show:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDelegate.mReader setDelegate:self];
        
        if (appDelegate.mReader == nil) {
            return;
        }
        
        mapTags = [[NSMutableDictionary alloc] init];
        
        mTotalTagCount = 0;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.storedcountTextField.text = [NSString stringWithFormat:@"%ld",mTotalTagCount];
            if ([appDelegate.mReader getAction] != CommandStop){
                [_loadBtn setEnabled:NO];
            }
//            [AppDelegate dismissGlobalHUD];
//            [HUD hide:YES];
//            [HUD removeFromSuperview];
        });
    });

}
- (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];
}
- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    dispatch_async(dispatch_get_main_queue(), ^{
//        self.storedcountTextField.text = [NSString stringWithFormat:@"%ld",mTotalTagCount];
        [AppDelegate dismissGlobalHUD];
        [HUD hide:YES];
        [HUD removeFromSuperview];
    });

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

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
}
- (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.
}
*/
-(void)changedActionState:(CommandType)action {
    if (action == CommandStop) {
        [_loadBtn setEnabled:YES];
        isload = 0;
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppDelegate dismissGlobalHUD];
            [HUD hide:YES];
            [HUD removeFromSuperview];
        });

    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.storedData.count;
}
#pragma mark - UITableViewDelegate
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    StoredDataTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoredDataCell" forIndexPath:indexPath];
    
    EATagItem *item = nil;
        item = [self.storedData objectAtIndex:indexPath.row];
        
        if (item != nil){
                cell.storeddatavalue.text = item.tag;
                cell.serialLabel.text = item.extradata;
                cell.storeddatacount.text = [NSString stringWithFormat:@"%d",item.count];
        }
    cell.textLabel.font = [UIFont systemFontOfSize:15.0];
    return cell;
}
- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.storedData removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];
    [self.totalCountLabel setText:[NSString stringWithFormat:@"%d", (int)self.storedData.count]];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
#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];
                             
    }
}
- (void)readTagResult:(NSString *)tag extradata:(NSString *)extradata {
    if(!isload){
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        EATagItem *item = nil;
        mTotalTagCount++;
        if((item = (EATagItem*)[mapTags objectForKey:tag]) != nil) {
            item.count++;
        } else {
            item = [[EATagItem alloc] init];
            item.count = 1;
            item.tag = tag;
            item.extradata = extradata;
            [self.storedData addObject:item];
            [mapTags setObject:item forKey:tag];
        }
        
        [self.totalCountLabel setText:[NSString stringWithFormat:@"%d", (int)self.storedData.count]];
        [self.totalDataCountLabel  setText:[NSString stringWithFormat:@"%ld", mTotalTagCount]];
        self.storedcountTextField.text = [NSString stringWithFormat:@"%ld",mTotalTagCount];
    [self.tableView reloadData];
    });
    
}
#pragma mark - IBAction
- (IBAction)loadBtnTapped:(id)sender {
//    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
//    isload = 1;
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    HUD.labelText = @"Loading...";
    [self.navigationController.view addSubview:HUD];
    [HUD show:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        [self loadDatas];
    });
}
- (IBAction)clearBtnTapped:(id)sender {

            mTotalTagCount = 0;
            [self.storedData removeAllObjects];
            [mapTags removeAllObjects];
    
            [self.tableView reloadData];
            
            self.storedcountTextField.text = [NSString stringWithFormat:@"0"];
            [self.totalCountLabel setText:[NSString stringWithFormat:@"0"]];

}
- (IBAction)removeBtnTapped:(id)sender {

//    [AppDelegate showGlobalProgressHUDWithTitle:@"Removing..."];
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    HUD.labelText = @"Removing...";
    [self.navigationController.view addSubview:HUD];
    [HUD show:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

       appDelegate.mReader.deleteSaveData;

        dispatch_async(dispatch_get_main_queue(), ^{
            mTotalTagCount = 0;
            [self.storedData removeAllObjects];
            [mapTags removeAllObjects];
            
            [self.tableView reloadData];
            
            [self.totalCountLabel setText:[NSString stringWithFormat:@"0"]];

            self.storedcountTextField.text = [NSString stringWithFormat:@"0"];
            
        });
    });
}
#pragma mark - Getters
-(NSMutableArray *)storedData {
    if(_storedData == nil) {
        _storedData = [[NSMutableArray alloc] init];
    }
    return _storedData;
}

#pragma mark - Costom
- (void)loadDatas{
    mTotalTagCount = 0;
    
    [mapTags removeAllObjects];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.storedData removeAllObjects];
        [self.totalCountLabel setText:[NSString stringWithFormat:@"%d", (int)self.storedData.count]];
    });
    isload = 1;
    appDelegate.mReader.getSaveData;
}

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