//
//  ViewController.m
//  wifiprint
//
//  Created by woosimsystems on 2021/05/21.
//  Copyright © 2021 Woosim Systems. All rights reserved.
//

#import "ViewController.h"
#import "ConnectViewController.h"
#import "woosim302-Swift.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *rcvDataLabel;

@end

extern NSString *WSSocketDidConnectNotification;
extern NSString *WSSocketDidDisconnectNotification;
extern NSString *WSSocketDataReceivedNotification;

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _socket = nil;
}

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

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(socketDidConnect:)
                                                 name:WSSocketDidConnectNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(socketDidDisconnect:)
                                                 name:WSSocketDidDisconnectNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                              selector:@selector(socketDataReceived:)
                                                  name:WSSocketDataReceivedNotification
                                                object:nil];
}

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

    [[NSNotificationCenter defaultCenter] removeObserver:self name:WSSocketDidConnectNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WSSocketDidDisconnectNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WSSocketDataReceivedNotification object:nil];
}

- (void)socketDidConnect:(NSNotification *)notification
{
    self.navigationItem.rightBarButtonItem.title = _socket.host;
}

- (void)socketDidDisconnect:(NSNotification *)notification
{
    _socket = nil;
    self.navigationItem.rightBarButtonItem.title = @"Connect";
}

- (void)socketDataReceived:(NSNotification *)notification
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        if ([self.socket readBytesAvailable] > 0) {
            NSInteger bytesAvailable = 0;
            NSMutableData *rcvData = [[NSMutableData alloc] init];
            while ((bytesAvailable = [self.socket readBytesAvailable]) > 0) {
                NSData *data = [self.socket readData:bytesAvailable];
                if (data) {
                    [rcvData appendData:data];
                }
            }
            WSPacket *packet = [[WSPacket alloc] init:rcvData];
            if ([packet packetType] == PacketTypeMSR) {
                NSArray *tracks = [NSArray arrayWithArray:[packet packetData]];
                NSMutableString *string = [NSMutableString stringWithString:@"MSR Track 1\r\n"];
                [string appendString:[[NSString alloc] initWithData:[tracks objectAtIndex:0] encoding:NSASCIIStringEncoding]];
                [string appendString:@"\r\n\nMSR Track 2\r\n"];
                [string appendString:[[NSString alloc] initWithData:[tracks objectAtIndex:1] encoding:NSASCIIStringEncoding]];
                [string appendString:@"\r\n\nMSR Track 3\r\n"];
                [string appendString:[[NSString alloc] initWithData:[tracks objectAtIndex:2] encoding:NSASCIIStringEncoding]];
                self.rcvDataLabel.text = string;
            } else {
                self.rcvDataLabel.text = [[NSString alloc] initWithString:[packet packetData]];
            }
        }
    });
}

- (IBAction)connectDevice:(id)sender {
    if (_socket == nil) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main"
                                                             bundle:nil];
        ConnectViewController *connectVC = [storyboard instantiateViewControllerWithIdentifier:@"connectVCID"];
        if (connectVC != nil) {
            [self presentViewController:connectVC animated:YES completion:nil];
        }
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Close Connection"
                                                                       message:@"Do you want to close connection?"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Yes"
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction *action)
        {
            [self.socket disconnect];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"No"
                                                               style:UIAlertActionStyleDefault
                                                             handler:nil];
        [alert addAction:okAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (IBAction)printText:(id)sender {
    NSMutableData *data = [[NSMutableData alloc]init];
    [data appendData:[WSCmd initPrinter]];
    [data appendData:[WSCmd alignText:AlignTypeCenter]];
    [data appendData:[WSCmd extendFontWithWidth:2 height:2]];
    [data appendData:[@"Receipt" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[WSCmd alignText:AlignTypeLeft]];
    [data appendData:[WSCmd extendFontWithWidth:1 height:1]];
    [data appendData:[WSCmd printData]];
    [data appendData:[@"NAME" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[WSCmd alignText:AlignTypeRight]];
    [data appendData:[@"Woosim Coffee\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[WSCmd alignText:AlignTypeLeft]];
    [data appendData:[@"MASTER" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[WSCmd alignText:AlignTypeRight]];
    [data appendData:[@"Gil-dong Hong\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[WSCmd alignText:AlignTypeLeft]];
    [data appendData:[@"ADDRESS" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[WSCmd alignText:AlignTypeRight]];
    [data appendData:[@"#60, Sandan-ro\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[@"388beon-gil, Galsan-myeon\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[@"Hongseong-gun, Chungnam-do\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[@"Republic of Korea\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[WSCmd alignText:AlignTypeLeft]];
    [data appendData:[@"HELP DESK" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[WSCmd alignText:AlignTypeRight]];
    [data appendData:[@"+82-41-339-3700\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[WSCmd alignText:AlignTypeLeft]];
    [data appendData:[@"--------------------------------\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[@"Cafe Mocha          2       4.50\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[@"Cafe Latte          1       4.00\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[@"Cappucino           1       4.00\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[@"--------------------------------\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[@"Total                     $17.00\n" dataUsingEncoding:NSASCIIStringEncoding]];
    [data appendData:[WSCmd printFeedWithLine:3]];
    [_socket writeData:data];
}

- (IBAction)printImage:(id)sender {
    NSMutableData *data = [[NSMutableData alloc]init];
    [data appendData:[WSCmd initPrinter]];
    UIImage *logo = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"logo" ofType:@"bmp"]];
    [data appendData:[WSImage printImage:logo dithering:NO compress:NO]];
    [data appendData:[WSCmd printFeedWithLine:3]];
    [_socket writeData:data];
}

- (IBAction)getDeviceName:(id)sender {
    _rcvDataLabel.text = @"";
    [_socket writeData:[WSCmd requestDeviceName]];
}

- (IBAction)getStatus:(id)sender {
    _rcvDataLabel.text = @"";
    [_socket writeData:[WSCmd requestStatus]];
}

@end
