//
//  CSVExportTableViewController.m
//  AsReaderLR
//
//  Created by mac on 2018/11/27.
//  Copyright © 2018年 asterisk. All rights reserved.
//

#import "CSVExportTableViewController.h"
#import "AppDelegate.h"

@interface CSVExportTableViewController ()<UIDocumentInteractionControllerDelegate>
@property(nonatomic,strong)UIDocumentInteractionController *documentController;
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)NSFileManager *fileManager;
@property (nonatomic, strong)NSString *filePath;
@end

@implementation CSVExportTableViewController {
    AppDelegate *appDelegate;
}

- (void)viewDidAppear:(BOOL)animated{
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
 
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(AsReaderGUNDisconnected:) name:@"AsReaderGUNDisconnected" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    _dataArray = [NSMutableArray array];
    _fileManager = [NSFileManager defaultManager];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    _filePath = @"";
    if ([_typeStr isEqualToString:@"csvInven"]) {
        _filePath = [path stringByAppendingPathComponent:@"RFID"];
         self.navigationItem.title = @"CSV List";
    } else if ([_typeStr isEqualToString:@"csvBarcode"]) {
        _filePath = [path stringByAppendingPathComponent:@"Barcode"];
         self.navigationItem.title = @"CSV List";
    } else if ([_typeStr isEqualToString:@"excelInven"]) {
        _filePath = [path stringByAppendingPathComponent:@"RFID"];
         self.navigationItem.title = @"Excel List";
    } else if ([_typeStr isEqualToString:@"excelBarcode"]) {
        _filePath = [path stringByAppendingPathComponent:@"Barcode"];
         self.navigationItem.title = @"Excel List";
    }
    [self datasource];
}

- (void)datasource {
    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading"];
    [_dataArray removeAllObjects];
    NSString *fileStr = _filePath;
    NSMutableArray *array = [NSMutableArray array];
    NSMutableArray *arr = [NSMutableArray array];
    NSMutableArray *fileNameArray = [NSMutableArray array];

    NSDirectoryEnumerator *enumerator;
    enumerator = [_fileManager enumeratorAtPath:fileStr];
    while((fileStr = [enumerator nextObject]) != nil) {
        [array addObject:fileStr];
    }
    if (array && array.count != 0) {
        for (NSString *str in array) {
            if ([_typeStr isEqualToString:@"csvInven"]) {
                if ([@"csv" isEqualToString:[str pathExtension]]) {
                    [arr addObject:str];
                }
            } else if ([_typeStr isEqualToString:@"csvBarcode"]) {
                if ([@"csv" isEqualToString:[str pathExtension]]) {
                    [arr addObject:str];
                }
            } else if ([_typeStr isEqualToString:@"excelInven"]) {
                if ([@"xlsx" isEqualToString:[str pathExtension]]) {
                    [arr addObject:str];
                }
            } else if ([_typeStr isEqualToString:@"excelBarcode"]) {
                if ([@"xlsx" isEqualToString:[str pathExtension]]) {
                    [arr addObject:str];
                }
            }
        }
    }
    
    if (arr && arr.count != 0) {
        for (NSString *str in arr) {
            NSString *string;
            if ([_typeStr isEqualToString:@"csvInven"]) {
                string = [str substringWithRange:NSMakeRange(5, 14)];
                [fileNameArray addObject:string];
            } else if ([_typeStr isEqualToString:@"csvBarcode"]) {
                string = [str substringWithRange:NSMakeRange(8, 14)];
                [fileNameArray addObject:string];
            } else if ([_typeStr isEqualToString:@"excelInven"]) {
                string = [str substringWithRange:NSMakeRange(5, 14)];
                [fileNameArray addObject:string];
            } else if ([_typeStr isEqualToString:@"excelBarcode"]) {
                string = [str substringWithRange:NSMakeRange(8, 14)];
                [fileNameArray addObject:string];
            }
        }
    }
    
    
    [fileNameArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return NSOrderedDescending;
        } else {
            return NSOrderedAscending;

        }
     }];

    NSLog(@"fileNameArray ==== %@", fileNameArray);
    
    for (NSString *str in fileNameArray) {
        for (NSString *string in arr) {
            if ([string containsString:str]) {
                [_dataArray addObject:string];
            }
        }
        
    }
    [self.tableView reloadData];
    [AppDelegate dismissGlobalHUD];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

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


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"tableViewCell"];
    }
    NSString *fileName = [_dataArray objectAtIndex:indexPath.row];
    fileName = [fileName lastPathComponent];
    cell.textLabel.text = fileName;
    return cell;
}

- (NSArray*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
                                          {
                                              [tableView setEditing:NO animated:YES];
                                              NSString *fileName = [_dataArray objectAtIndex:indexPath.row];
                                              fileName = [_filePath stringByAppendingString:[NSString stringWithFormat:@"/%@", fileName]];
                                              if ([_fileManager fileExistsAtPath:fileName]) {
                                                  NSError *error;
                                                  [_fileManager removeItemAtPath:fileName error:&error];
                                                  NSLog(@"error ===== %@", error);
                                                  [self datasource];
                                              }
                                              
                                          }];
    
    
    deleteAction.backgroundColor = [UIColor redColor];
    return @[deleteAction];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *fileName = [_dataArray objectAtIndex:indexPath.row];
    fileName = [_filePath stringByAppendingString:[NSString stringWithFormat:@"/%@", fileName]];
    if ([_fileManager fileExistsAtPath:fileName]) {
         _documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:fileName]];
         _documentController.delegate = self;
         [_documentController presentPreviewAnimated:YES];
     }
}


- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
    return self;
}

- (void)AsReaderGUNDisconnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        appDelegate.mReader = nil;
        [self nowViewWillDisappear];
        [self dismissViewControllerAnimated:YES completion:nil];
        [NSThread sleepForTimeInterval:0.2];
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}

- (void)nowViewWillDisappear{
    if (appDelegate.insertOperation.operationCount > 0) {
        [AppDelegate dismissGlobalHUD];
        [AppDelegate showGlobalProgressHUDWithTitle:@"Data Insert..."];
        [CATransaction commit];
        NSLog(@"wait");
        while (true) {
            [NSThread sleepForTimeInterval:0.5];
            if (appDelegate.insertOperation.operationCount==0) {
                NSLog(@"wait");
                break;
            }
        }
        [AppDelegate dismissGlobalHUD];
        [CATransaction commit];
    }else{
        return;
    }
}

@end












