//
//  FirstViewController.m
//  SIIMpaPrinterSample
//

#import "FirstViewController.h"
#import "PrinterManager.h"
#import "ValueManager.h"
#import "SiiPrinter.h"
#import "PrinterListViewController.h"
#import "PrintPDFViewController.h"
#import "UniformTypeIdentifiers/UniformTypeIdentifiers.h"
#import "SIIMpaPrinterManager/SIIMpaPrinterManager.h"

@interface FirstViewController () <UIDocumentPickerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
    dispatch_queue_t _gcd_printerManagerQueue;
    UIView *_indicatorView;
}

@property (weak, nonatomic) IBOutlet UITextField *addressTextField;
@property (strong, nonatomic) IBOutlet UITextField *connectTypeTextField;

@property (strong, nonatomic) SiiPrinter* printer;
@end

@implementation FirstViewController

+ (void) initialize {
    [super initialize];
    [ValueManager setCurrentStringValue:KEY_TYPE_ADDRESS value:VALUE_TYPE_ADDRESS];
    [ValueManager setCurrentStringValue:KEY_TYPE_PORTTYPE value:VALUE_TYPE_PORTTYPE];
    [ValueManager setCurrentStringValue:KEY_TYPE_PRINTERMODEL value:VALUE_TYPE_PORTTYPE];
    [self createSampleFile];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [PrinterManager InitialSetting:self];
    [self initIndicatorView];
    _gcd_printerManagerQueue = dispatch_queue_create("com.sii-ps.mpaPrinterManager", DISPATCH_QUEUE_SERIAL);
    NSString *address  = [ValueManager getCurrentStringValue:KEY_TYPE_ADDRESS];
    NSString *modelName = [ValueManager getCurrentStringValue:KEY_TYPE_PRINTERMODEL];
    NSString *portType = [ValueManager getCurrentStringValue:KEY_TYPE_PORTTYPE];
    
    self.printer = [[SiiPrinter alloc] init:address modelName:modelName portType:portType];
    _addressTextField.text = address;
    _connectTypeTextField.text = portType;
}

- (IBAction)standardModeSampleButtonOnClicked:(id)sender {
    [self startLoadingView];
    dispatch_async(dispatch_queue_create("com.sii-ps.printStandardModeReceipt", DISPATCH_QUEUE_SERIAL), ^{
        BOOL success = [PrinterManager printStandardModeReceipt];
        [self stopLoadingView];
        if (success == NO) {
            [self showMessageBox:@"" message:[NSString stringWithFormat:@"%@%@", @"Attempt to print receipt failed.\n ErrorCode : ", [PrinterManager getErrorCodeText]]];
        }
    });
}

- (IBAction)pageModeSampleButtonOnClicked:(id)sender {
    [self startLoadingView];
    dispatch_async(dispatch_queue_create("com.sii-ps.printPageModeReceipt", DISPATCH_QUEUE_SERIAL), ^{
        BOOL success = [PrinterManager printPageModeReceipt];
        [self stopLoadingView];
        if (success == NO) {
            [self showMessageBox:@"" message:[NSString stringWithFormat:@"%@%@", @"Attempt to print receipt failed.\n ErrorCode : ", [PrinterManager getErrorCodeText]]];
        }
    });
}

- (IBAction)sendFileButtonOnClicked:(id)sender {
    // The sendDataFile function allows following file extensions:
    // .bmp, .jpg/.jpeg, .png, .txt, .bin, .dat, .html
    NSArray<UTType*> *types = @[
        [UTType typeWithFilenameExtension:@"bmp"],
        [UTType typeWithFilenameExtension:@"jpg"],
        [UTType typeWithFilenameExtension:@"jpeg"],
        [UTType typeWithFilenameExtension:@"png"],
        [UTType typeWithFilenameExtension:@"txt"],
        [UTType typeWithFilenameExtension:@"bin"],
        [UTType typeWithFilenameExtension:@"dat"],
        [UTType typeWithFilenameExtension:@"html"],
        [UTType typeWithFilenameExtension:@"htm"],
    ];
    // show a document picker
    UIDocumentPickerViewController *documentPicker =
    [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:types];
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
    documentPicker.view.tag = 1;
    [self presentViewController:documentPicker animated:YES completion:nil];
}

- (IBAction)printPDFButtonOnClicked:(id)sender {
    // The printPDF function allows following file extensions:
    // .pdf
    NSArray<UTType*> *types = @[
        UTTypePDF
    ];
    // show a document picker
    UIDocumentPickerViewController *documentPicker =
    [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:types];
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
    documentPicker.view.tag = 2;
    [self presentViewController:documentPicker animated:YES completion:nil];
}

- (IBAction)firstViewReturnActionForSegue:(UIStoryboardSegue *)segue {
    PrinterListViewController *printerListView = segue.sourceViewController;
    // Get selected printer from printer list view
    self.printer = printerListView.printer;
    _addressTextField.text = self.printer.address;
    _connectTypeTextField.text = self.printer.portType;
    // Set user default
    [ValueManager setCurrentStringValue:KEY_TYPE_ADDRESS value:self.printer.address];
    [ValueManager setCurrentStringValue:KEY_TYPE_PORTTYPE value:self.printer.portType];
    [ValueManager setCurrentStringValue:KEY_TYPE_PRINTERMODEL value:self.printer.modelName];
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    // When a file is picked
    NSURL *file = urls.firstObject;
    NSInteger tag = controller.view.tag;
    if (tag == 1){
        // Get selected file's path from url
        NSString *fileName = [file lastPathComponent];
        NSString *ext = [[file pathExtension] lowercaseString];
        if ([ext isEqual: @"bmp"] || [ext isEqual: @"jpeg"] || [ext isEqual: @"jpg"] || [ext  isEqual: @"png"]) {
            NSString *message = [NSString stringWithFormat:@"%@%@%@", @"Send file: ",fileName, @"\nSpecify dithering for printing."];
            [self showSendDataFileAlert:message file:file isImageFile:YES];
        } else if ([ext isEqual: @"txt"] || [ext isEqual: @"dat"] || [ext isEqual: @"bin"] || [ext isEqual:@"htm"] || [ext isEqual:@"html"]) {
            NSString *message = [NSString stringWithFormat:@"%@%@", @"Send file: ",fileName];
            [self showSendDataFileAlert:message file:file isImageFile:NO];
        } else {
            [self showMessageBox:@"SendDataFile" message:@"Unsupport file extension!"];
        }
    } else if (tag == 2){
        UINavigationController *navigationController = [self.storyboard instantiateViewControllerWithIdentifier:@"PrintPDFNavigationController"];
        PrintPDFViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PrintPDFViewController"];
        viewController.file = file;
        viewController.title = @"PrintPDF";
        [navigationController setViewControllers:[NSArray arrayWithObject:viewController]];
        navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
        [self presentViewController:navigationController animated:YES completion:nil];
    }
}

- (void)sendDataFile:(NSURL *)file dithering:(BOOL)dithering {
    NSInteger dither;
    if (dithering == YES) {
        dither = SII_MPM_DITHERING_ERRORDIFFUSION;
    } else {
        dither = SII_MPM_DITHERING_DISABLE;
    }
    [self startLoadingView];
    dispatch_async(_gcd_printerManagerQueue, ^{
        BOOL success = YES;
        if ([file startAccessingSecurityScopedResource] == YES) {
            NSString *filePath = [file path];
            // Send file path to printer
            success = [PrinterManager sendDataFile:filePath dithering:dither];
            [file stopAccessingSecurityScopedResource];
        } else {
            success = NO;
        }
        if (success == NO) {
            [self showMessageBox:@"" message:[NSString stringWithFormat:@"%@%@", @"Attempt to send file failed.\n ErrorCode : ", [PrinterManager getErrorCodeText]]];
        }
        [self stopLoadingView];
    });
}

#pragma mark - Private

- (void)initIndicatorView {
    _indicatorView = [[NSBundle mainBundle] loadNibNamed:@"IndicatorView" owner:self options:nil][0];
    _indicatorView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    _indicatorView.hidden = YES;
    [self.view addSubview:_indicatorView];
}

- (void)startLoadingView {
    dispatch_async(dispatch_get_main_queue(), ^{
        self->_indicatorView.hidden = NO;
    });
}

- (void)stopLoadingView {
    dispatch_async(dispatch_get_main_queue(), ^{
        self->_indicatorView.hidden = YES;
    });
}

- (void)showMessageBox:(NSString *)title message:(NSString *)message {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alertController =  [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"Close" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    });
}

- (void)showSendDataFileAlert:(NSString *)message file:(NSURL *)file isImageFile:(BOOL)isImageFile {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alertController =  [UIAlertController alertControllerWithTitle:@"SendDataFile" message:message preferredStyle:UIAlertControllerStyleAlert];
        if (isImageFile == YES) {
            [alertController addAction:[UIAlertAction actionWithTitle:@"Dithering Enable" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [self sendDataFile:file dithering:YES];
            }]];
            [alertController addAction:[UIAlertAction actionWithTitle:@"Dithering Disable" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [self sendDataFile:file dithering:NO];
            }]];
            [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            }]];
        } else {
            [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            }]];
            [alertController addAction:[UIAlertAction actionWithTitle:@"Send" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [self sendDataFile:file dithering:NO];
            }]];
            
        }
        [self presentViewController:alertController animated:YES completion:nil];
    });
}

+ (void)createSampleFile {
    NSString *documentsDirectoryPath = [NSString stringWithFormat:@"%@/Documents/", NSHomeDirectory()];
    NSString *filePath = [NSString stringWithFormat:@"%@Sample.txt", documentsDirectoryPath];
    NSFileManager *fileManager =[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] == NO) {
        BOOL result = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
        if (result == YES) {
            NSString *text = @"SampleText\n";
            [text writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
    }
}
@end
