//
//  IHRPrinterVC.m
//
//

#import "IHRPrinterVC.h"
#import "IHRPrinterSDK.h"

typedef NS_ENUM(NSInteger, ConnectType) {
    NONE = 0,   //None
    BT,         //Bluetooth
    WIFI,       //WiFi
};

@interface IHRPrinterVC ()<UITextFieldDelegate, IHRBLEManagerDelegate, IHRWIFIManagerDelegate>

// connect state tip
@property (weak, nonatomic) IBOutlet UILabel *connectState;

// wifi
@property (weak, nonatomic) IBOutlet UITextField *wifiTextField;

// connect type
@property (assign, nonatomic) ConnectType connectType;

// indicator
@property (strong, nonatomic) UIActivityIndicatorView *indicator;

// disconnect button
@property (weak, nonatomic) IBOutlet UIButton *disconnectButton;

// print text button
@property (weak, nonatomic) IBOutlet UIButton *printTextButton;

// print qrcode button
@property (weak, nonatomic) IBOutlet UIButton *printQRCodeButton;

// print barcode button
@property (weak, nonatomic) IBOutlet UIButton *printBarCodeButton;

// print picture button
@property (weak, nonatomic) IBOutlet UIButton *printPictureButton;

// receipts button
@property (weak, nonatomic) IBOutlet UIButton *receiptsButton;

// scan bluetooth button
@property (weak, nonatomic) IBOutlet UIButton *scanButton;

// connnect wifi button
@property (weak, nonatomic) IBOutlet UIButton *connectButton;

@end

@implementation IHRPrinterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [IHRBLEManager sharedInstance].delegate = self;
    [IHRWIFIManager sharedInstance].delegate = self;
    
    self.wifiTextField.delegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(IHRConnectionBT) name:@"IHR_CONNECTION_BT" object:nil];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardDismiss)];
    self.view.userInteractionEnabled = YES;
    [self.view addGestureRecognizer:tap];
    
    [self initView];
    
}

- (void)initView {
    _indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _indicator.center = self.view.center;
    [self.view addSubview:self.indicator];
    
    _disconnectButton.layer.cornerRadius = 10.f;
    _printTextButton.layer.cornerRadius = 10.f;
    _printQRCodeButton.layer.cornerRadius = 10.f;
    _printBarCodeButton.layer.cornerRadius = 10.f;
    _printPictureButton.layer.cornerRadius = 10.f;
    _receiptsButton.layer.cornerRadius = 10.f;
    _scanButton.layer.cornerRadius = 10.f;
    _connectButton.layer.cornerRadius = 10.f;
}

- (void)dealloc {
    [[IHRBLEManager sharedInstance] removeDelegate:self];
    [[IHRWIFIManager sharedInstance] removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self discount:nil];
}

- (void)IHRConnectionBT {
    if ([IHRBLEManager sharedInstance].writePeripheral) {
        _connectState.text = @"IHR";
    }
}

- (void)keyboardDismiss {
    [self.wifiTextField resignFirstResponder];
}


#pragma mark - Action

//discount manual
- (IBAction)discount:(UIButton *)sender {
    if (self.connectType == BT) {
        [[IHRBLEManager sharedInstance] disconnectRootPeripheral];
    } else if (self.connectType == WIFI) {
        [[IHRWIFIManager sharedInstance] disconnect];
    } else {
        return;
    }
}

// wifi connect
- (IBAction)wifiConnectAction:(UIButton *)sender {
    if (self.wifiTextField.text.length == 0) {
        [self.view makeToast:@"please input wifi address" duration:1.f position:CSToastPositionCenter];
    }
    
    if ([IHRWIFIManager sharedInstance].isConnect) {
        [[IHRWIFIManager sharedInstance] disconnect];
    }
    
    [self keyboardDismiss];
    [self.indicator startAnimating];
    [[IHRWIFIManager sharedInstance] connectWithHost:self.wifiTextField.text port:9100];
}

- (void)buttonStateOn {
    _disconnectButton.enabled = YES;
    _printTextButton.enabled = YES;
    _printQRCodeButton.enabled = YES;
    _printBarCodeButton.enabled = YES;
    _printPictureButton.enabled = YES;
    _receiptsButton.enabled = YES;
}

- (void)buttonStateOff {
    _disconnectButton.enabled = NO;
    _printTextButton.enabled = NO;
    _printQRCodeButton.enabled = NO;
    _printBarCodeButton.enabled = NO;
    _printPictureButton.enabled = NO;
    _receiptsButton.enabled = NO;
}


#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}


#pragma mark - IHRBLEManagerDelegate

//connect success
- (void)IHRbleConnectPeripheral:(CBPeripheral *)peripheral {
    _connectType = BT;
    
    [self buttonStateOn];
}

//bluetooth print success
- (void)IHRbleWriteValueForCharacteristic:(CBCharacteristic *)character error:(NSError *)error {
    [self.indicator stopAnimating];
}

// disconnect
- (void)IHRbleDisconnectPeripheral:(CBPeripheral *)peripheral {
    if ([IHRWIFIManager sharedInstance].isConnect) {
        _connectType = WIFI;
        _connectState.text = @"IHR";
    } else {
        _connectType = NONE;
        _connectState.text = @"NONE";
    }
    
    [self buttonStateOff];
    [self.indicator stopAnimating];
}


#pragma mark - IHRWIFIManagerDelegate

//connected success
- (void)IHRwifiConnectedToHost:(NSString *)host port:(UInt16)port {
    _connectType = WIFI;
    _connectState.text = @"IHR";
    
    [self buttonStateOn];
    [self.indicator stopAnimating];
    [self.view makeToast:@"connect success" duration:1.f position:CSToastPositionCenter];
}

//disconnected mean error
- (void)IHRwifiDisconnectWithError:(NSError *)error {
    if ([IHRBLEManager sharedInstance].isConnect) {
        _connectType = BT;
        _connectState.text = @"IHR";
    } else {
        _connectType = NONE;
        _connectState.text = @"NONE";
    }
    
    [self buttonStateOff];
    [self.indicator stopAnimating];
    [self.view makeToast:[NSString stringWithFormat:@"%@", error] duration:2.f position:CSToastPositionCenter];
}

//disconnected manual
- (void)IHRwifiDisconnectForManual {
    if ([IHRBLEManager sharedInstance].isConnect) {
        _connectType = BT;
        _connectState.text = @"IHR";
    } else {
        _connectType = NONE;
        _connectState.text = @"NONE";
    }
    
    [self buttonStateOff];
}

//print success
- (void)IHRwifiWriteValueWithTag:(long)tag {
    [self.indicator stopAnimating];
}


#pragma mark - Test Print

- (void)printWithData:(NSData *)printData {
    switch (self.connectType) {
        case NONE:
            [self.view makeToast:@"please connect printer" duration:1.f position:CSToastPositionCenter];
            break;
            
        case WIFI:
        {
            [[IHRWIFIManager sharedInstance] writeCommandWithData:printData];
        }
            break;
            
        case BT:
        {
            [[IHRBLEManager sharedInstance] writeCommandWithData:printData];
        }
            break;
            
        default:
            break;
    }
}

- (IBAction)printTextAction:(id)sender {
    NSMutableData *dataM = [NSMutableData dataWithData:[IHR810Command initializePrinter]];
    NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    [dataM appendData: [@"123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" dataUsingEncoding: gbkEncoding]];
    [dataM appendData:[IHR810Command printAndFeedForwardWhitN:7]];
    [dataM appendData:[IHR810Command selectCutPageModelAndCutpage:1]];

    [self printWithData:dataM];
}

- (IBAction)printQRCodeAction:(id)sender {
    NSMutableData *dataM = [NSMutableData dataWithData:[IHR810Command initializePrinter]];
    [dataM appendData:[IHR810Command selectAlignment:1]];
    [dataM appendData:[IHR810Command printQRCode:6 level:48 code:@"www.google.com" useEnCodeing:NSASCIIStringEncoding]];
    [dataM appendData:[IHR810Command printAndFeedForwardWhitN:6]];
    [dataM appendData:[IHR810Command selectCutPageModelAndCutpage:1]];
    
    [self printWithData:dataM];
}

- (IBAction)printBarCodeAction:(UIButton *)sender {
    NSMutableData *dataM = [NSMutableData dataWithData:[IHR810Command initializePrinter]];
    [dataM appendData:[IHR810Command selectHRICharactersPrintPosition:2]];
    [dataM appendData:[IHR810Command selectAlignment:1]];
    [dataM appendData:[IHR810Command printBarcodeWithM:5 andContent:@"12345678" useEnCodeing:NSASCIIStringEncoding]];
    [dataM appendData:[IHR810Command printAndFeedForwardWhitN:6]];
    [dataM appendData:[IHR810Command selectCutPageModelAndCutpage:1]];
    
    [self printWithData:dataM];
}

- (IBAction)printPictureAction:(id)sender {
    UIImage *img = [UIImage imageNamed:@"image"];
    
    NSMutableData *dataM = [NSMutableData dataWithData:[IHR810Command initializePrinter]];
    [dataM appendData:[IHR810Command selectAlignment:1]];
    [dataM appendData:[IHR810Command printRasteBmpWithM:RasterNolmorWH andImage:img andType:Dithering]];
    [dataM appendData:[IHR810Command printAndFeedForwardWhitN:6]];
    [dataM appendData:[IHR810Command selectCutPageModelAndCutpage:1]];
    
    [self printWithData:dataM];
}

@end
