//
//  GlobalController.m
//  JXPrinterDemo
//
//  Created by 贾俊伟 on 2022/6/22.
//

#import "GlobalController.h"
#import <JXPrinter/JXPrinter.h>
#import "DeviceListController.h"
#import "CmdModel.h"
#import "GlobalPagePrinter.h"
#import "GlobalLinePrinter.h"
#import "JXProgressHUD.h"

@interface GlobalController ()<
UITableViewDelegate,
UITableViewDataSource
>

@property (nonatomic, strong) UIButton *rightBarButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<NSString *> *headerArray;
@property (nonatomic, strong) NSMutableArray<NSArray<CmdModel *> *> *dataArray;

@property (nonatomic, strong) GlobalPagePrinter *page;
@property (nonatomic, strong) GlobalLinePrinter *line;
@property (nonatomic, strong) CBPeripheral *peripheral;

@end

@implementation GlobalController

static NSString * const itemId = @"item";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Global";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBarButton];
    [self.view addSubview:self.tableView];
    // show log
    [JXBleManager setLogEnable:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSString *title = [JXBleManager bleManager].isConnectBle || [JXSocketManager manager].isConnected ? NSLocalizedString(@"Connected", nil) : NSLocalizedString(@"Scan", nil);
    [self.rightBarButton setTitle:title forState:UIControlStateNormal];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(10, 0, [UIScreen mainScreen].bounds.size.width-10, [UIScreen mainScreen].bounds.size.height);
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:itemId forIndexPath:indexPath];
    cell.textLabel.text = self.dataArray[indexPath.section][indexPath.row].cmdName;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.textColor = [UIColor colorWithWhite:0 alpha:0.7];
    cell.imageView.image = [UIImage imageNamed:self.dataArray[indexPath.section][indexPath.row].imageName];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 判断当前是否连接打印机
    if (![JXBleManager bleManager].isConnectBle && ![JXSocketManager manager].isConnected) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:NSLocalizedString(@"Unconnected", nil) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *done = [UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", nil) style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:done];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    JXConnectType type = [JXSocketManager manager].isConnected ? JXConnectTypeTcp : JXConnectTypeBle;
    self.page.connectType = type;
    self.line.connectType = type;
    [JXProgressHUD showHUD];
    CmdModel *model = self.dataArray[indexPath.section][indexPath.row];
    if ([model.target respondsToSelector:model.action]) {
        [model.target performSelector:model.action];
    }
    
    if (indexPath.section == 1 || indexPath.section == 3) {
        // wait print complete
        [self p_checkPrinterStatus];
    } else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [JXProgressHUD hideHUD];
        });
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel *titleLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
    titleLb.backgroundColor = [UIColor whiteColor];
    titleLb.text = self.headerArray[section];
    titleLb.textColor = [UIColor blackColor];
    titleLb.font = [UIFont systemFontOfSize:16];
    return titleLb;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

#pragma mark - Click

- (void)rightBarButtonClick {
    DeviceListController *listVC = [[DeviceListController alloc] init];
    [self.navigationController pushViewController:listVC animated:YES];
}

- (void)unlockPrinter {
    BOOL unlockSuccess = [[JXPrinterManager printerManager] unlock];
    [JXProgressHUD hideHUD];
    [JXProgressHUD toast:[NSString stringWithFormat:@"unlock %@", unlockSuccess ? @"success" : @"fail"]];
}

- (void)printCheckPage {
    BOOL printSuccess = [[JXPrinterManager printerManager] printCheckPage];
    [JXProgressHUD hideHUD];
    [JXProgressHUD toast:[NSString stringWithFormat:@"print %@", printSuccess ? @"success" : @"fail"]];
}

- (void)readBlePrintStatus {
    [[JXPrinterManager printerManager] readBlePrintStatus:30 success:^(PrintStatus blePrintStatus) {
        [JXProgressHUD hideHUD];
        switch (blePrintStatus) {
            case PrintStatusNoPaper:
                [JXProgressHUD toast:NSLocalizedString(@"NoPaper", nil) inView:self.view];
                break;
            case PrintStatusOverHeat:
                [JXProgressHUD toast:NSLocalizedString(@"Overheating", nil) inView:self.view];
                break;
            case PrintStatusBatteryLow:
                [JXProgressHUD toast:NSLocalizedString(@"LowPower", nil) inView:self.view];
                break;
            case PrintStatusPrinting:
                [JXProgressHUD toast:NSLocalizedString(@"Printing", nil) inView:self.view];
                break;
            case PrintStatusCoverOpen:
                [JXProgressHUD toast:NSLocalizedString(@"Open", nil) inView:self.view];
                break;
            default:
                [JXProgressHUD toast:NSLocalizedString(@"Leisure", nil) inView:self.view];
                break;
        }
    } fail:^{
        [JXProgressHUD hideHUD];
        [JXProgressHUD toast:NSLocalizedString(@"QueryFail", nil) inView:self.view];
    }];
}

- (void)p_checkPrinterStatus {
    static NSInteger retryTimes = 0;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[JXBleManager bleManager] readBlePrintStatus:50 success:^(PrintStatus blePrintStatus) {
            if ((blePrintStatus == PrintStatusPrinting) && (retryTimes < 60)) {
                retryTimes++;
                [self p_checkPrinterStatus];
                return;
            }
            retryTimes = 0;
            [JXProgressHUD hideHUD];
            if (blePrintStatus == PrintStatusOk || blePrintStatus == PrintStatusNoError) {
                [JXProgressHUD toast:@"print success"];
            }
        } fail:^{
            retryTimes = 0;
            [JXProgressHUD hideHUD];
        }];
    });
}

#pragma mark - Getter

- (UIButton *)rightBarButton {
    if (!_rightBarButton) {
        _rightBarButton = [[UIButton alloc] init];
        _rightBarButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_rightBarButton setTitle:NSLocalizedString(@"Scan", nil) forState:UIControlStateNormal];
        [_rightBarButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_rightBarButton addTarget:self action:@selector(rightBarButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBarButton;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:itemId];
    }
    return _tableView;
}

- (NSMutableArray<NSString *> *)headerArray {
    if (!_headerArray) {
        _headerArray = [[NSMutableArray alloc] init];
    }
    return _headerArray;
}

- (NSMutableArray<NSArray<CmdModel *> *> *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
        // 打印机属性
        NSArray<CmdModel *> *printerCmds = @[
            [CmdModel modelWithCmdName:NSLocalizedString(@"PrinterStatus", nil) imageName:@"status" target:self action:@selector(readBlePrintStatus)],
            [CmdModel modelWithCmdName:NSLocalizedString(@"PrintCheckPage", nil) imageName:@"checkPage" target:self action:@selector(printCheckPage)],
            [CmdModel modelWithCmdName:NSLocalizedString(@"Unlock", nil) imageName:@"unlock" target:self action:@selector(unlockPrinter)],
        ];
        NSString *comprehensive = NSLocalizedString(@"Comprehensive", nil);
        NSString *box = NSLocalizedString(@"Box", nil);
        NSString *line = NSLocalizedString(@"Line", nil);
        NSString *text = NSLocalizedString(@"Text", nil);
        NSString *barcode = NSLocalizedString(@"Barcode", nil);
        NSString *QRCode = NSLocalizedString(@"QRCode", nil);
        NSString *image = NSLocalizedString(@"image", nil);
        NSString *curve = NSLocalizedString(@"Curve", nil);
        
        // image names
        NSString *allImage = @"all";
        NSString *rectImage = @"rect";
        NSString *lineImage = @"line";
        NSString *textImage = @"text";
        NSString *barcodeImage = @"barcode";
        NSString *qrcodeImage = @"qrcode";
        NSString *imageImage = @"image";
        NSString *curveImage = @"curve";
        
    
        
        // global page
        NSArray<CmdModel *> *pageCmds = @[
            [CmdModel modelWithCmdName:comprehensive imageName:allImage target:self.page action:@selector(printAll)],
            [CmdModel modelWithCmdName:text imageName:textImage target:self.page action:@selector(drawText)],
            [CmdModel modelWithCmdName:image imageName:imageImage target:self.page action:@selector(drawGraphic)],
            [CmdModel modelWithCmdName:barcode imageName:barcodeImage target:self.page action:@selector(drawBarCode)],
            [CmdModel modelWithCmdName:QRCode imageName:qrcodeImage target:self.page action:@selector(drawQrCode)],
            [CmdModel modelWithCmdName:line imageName:lineImage target:self.page action:@selector(drawLine)],
            [CmdModel modelWithCmdName:box imageName:rectImage target:self.page action:@selector(drawBox)],
        ];
        
        // global line
        NSArray<CmdModel *> *lineCmds = @[
            [CmdModel modelWithCmdName:comprehensive imageName:allImage target:self.line action:@selector(printAll)],
            [CmdModel modelWithCmdName:text imageName:textImage target:self.line action:@selector(printText)],
            [CmdModel modelWithCmdName:image imageName:imageImage target:self.line action:@selector(drawGraphic)],
            [CmdModel modelWithCmdName:barcode imageName:barcodeImage target:self.line action:@selector(drawBarCode)],
            [CmdModel modelWithCmdName:QRCode imageName:qrcodeImage target:self.line action:@selector(drawQrCode)],
            [CmdModel modelWithCmdName:line imageName:lineImage target:self.line action:@selector(drawLine)],
            [CmdModel modelWithCmdName:curve imageName:curveImage target:self.line action:@selector(drawLineSegments)],
        ];
        
        [_dataArray addObject:printerCmds];
        [self.headerArray addObject:NSLocalizedString(@"PrinterInfo", nil)];
    
        
        [_dataArray addObject:pageCmds];
        [self.headerArray addObject:@"Global page"];
        
        [_dataArray addObject:lineCmds];
        [self.headerArray addObject:@"Global line"];
    }
    return _dataArray;
}

- (GlobalPagePrinter *)page {
    if (!_page) {
        _page = [[GlobalPagePrinter alloc] init];
        _page.printWidth = 576;
    }
    return _page;
}

- (GlobalLinePrinter *)line {
    if (!_line) {
        _line = [[GlobalLinePrinter alloc] init];
        _line.printWidth = 384;
    }
    return _line;
}

@end
