//
//  PrintTextViewController.m
//  SIIMpaPrinterSample
//

#import "PrinterManager.h"
#import "PrintTextViewController.h"
#import "ValueManager.h"
#import "ValueViewController.h"

@interface PrintTextViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation PrintTextViewController {
    UIView *_indicatorView;
    ValueViewController *_viewController;
    NSInteger _sectionIndex;
    NSInteger _frameWidth;    
}

static NSUInteger const SIZE_OF_SECTION_TITLE_TABLE = 7;
static NSString *const SECTION_TITLE_TABLE[] = {
    TEXT_TEXT_SECTION,
    TEXT_FONT_SECTION,
    TEXT_SCALE_SECTION,
    TEXT_UNDERLINE_SECTION,
    TEXT_BOLD_SECTION,
    TEXT_REVERSE_SECTION,
    TEXT_ROTATION_SECTION
};

static NSUInteger const SIZE_OF_FONT_TABLE = 2;
static NSString *const FONT_TABLE[] = {
    TEXT_FONT_A,
    TEXT_FONT_B
};

static NSUInteger const SIZE_OF_SCALE_TABLE = 8;
static NSString *const SCALE_TABLE[] = {
    TEXT_SCALE_1,
    TEXT_SCALE_2,
    TEXT_SCALE_3,
    TEXT_SCALE_4,
    TEXT_SCALE_5,
    TEXT_SCALE_6,
    TEXT_SCALE_7,
    TEXT_SCALE_8
};

static NSUInteger const SIZE_OF_UNDERLINE_TABLE = 3;
static NSString *const UNDERLINE_TABLE[] = {
    TEXT_UNDERLINE_NONE,
    TEXT_UNDERLINE_1DOT,
    TEXT_UNDERLINE_2DOT
};

static NSUInteger const SIZE_OF_BOLD_TABLE = 2;
static NSString *const BOLD_TABLE[] = {
    TEXT_BOLD_OFF,
    TEXT_BOLD_ON
};

static NSUInteger const SIZE_OF_REVERSE_TABLE = 2;
static NSString *const REVERSE_TABLE[] = {
    TEXT_REVERSE_OFF,
    TEXT_REVERSE_ON
};

static NSUInteger const SIZE_OF_ROTATIONE_TABLE = 4;
static NSString *const ROTATION_TABLE[] = {
    TEXT_ROTATION_NONE,
    TEXT_ROTATION_90_TO_RIGHT,
    TEXT_ROTATION_180,
    TEXT_ROTATION_90_TO_LEFT
};

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _sectionIndex = -1;
    self.tableView.delegate = (id <UITableViewDelegate>)self;
    self.tableView.dataSource = (id <UITableViewDataSource>)self;
    [self initIndicatorView];
    [self setDefaultValue];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self reloadTableView];
    [self reloadViewSize];
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    //
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        [self reloadViewSize];
    } completion:nil];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return SIZE_OF_SECTION_TITLE_TABLE;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section < SIZE_OF_SECTION_TITLE_TABLE) {
        return SECTION_TITLE_TABLE[section];
    } else {
        return @"";
    }
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    cell.textLabel.text = @"";
    cell.textLabel.numberOfLines = 0;
    NSString *sectionTitle = SECTION_TITLE_TABLE[indexPath.section];
    if ([sectionTitle isEqualToString:TEXT_TEXT_SECTION]) {
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 0, _frameWidth - 20, cell.frame.size.height)];
        textField.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
        textField.returnKeyType = UIReturnKeyDone;
        textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        textField.tag = indexPath.section;
        textField.clearButtonMode = YES;
        [textField setDelegate:self];
        textField.text = [ValueManager getCurrentStringValue:KEY_TYPE_TEXT];
        [cell.contentView addSubview:textField];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
    } else if ([sectionTitle isEqualToString:TEXT_FONT_SECTION]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = [ValueManager getCurrentStringValue:KEY_TYPE_FONT];
    } else if ([sectionTitle isEqualToString:TEXT_SCALE_SECTION]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = [ValueManager getCurrentStringValue:KEY_TYPE_SCALE];
    } else if ([sectionTitle isEqualToString:TEXT_UNDERLINE_SECTION]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = [ValueManager getCurrentStringValue:KEY_TYPE_UNDERLINE];
    } else if ([sectionTitle isEqualToString:TEXT_BOLD_SECTION]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = [ValueManager getCurrentStringValue:KEY_TYPE_BOLD];
    } else if ([sectionTitle isEqualToString:TEXT_REVERSE_SECTION]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = [ValueManager getCurrentStringValue:KEY_TYPE_REVERSE];
    } else if ([sectionTitle isEqualToString:TEXT_ROTATION_SECTION]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = [ValueManager getCurrentStringValue:KEY_TYPE_ROTATION];
    }
    return cell;
}

#pragma mark - TextField
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    [ValueManager setCurrentStringValue:KEY_TYPE_TEXT value:textField.text];
    return YES;
}

#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    if (0 <= indexPath.section && indexPath.section < SIZE_OF_SECTION_TITLE_TABLE) {
        NSString *sectionTitle = SECTION_TITLE_TABLE[indexPath.section];
        _sectionIndex = indexPath.section;
        if ([sectionTitle isEqualToString:TEXT_FONT_SECTION]) {
            UITableViewCell *cell = sender;
            _viewController = [segue destinationViewController];
            NSMutableArray *valueData = [[NSMutableArray alloc] init];
            for (int i = 0; i < SIZE_OF_FONT_TABLE; i++) {
                [valueData addObject:FONT_TABLE[i]];
                if ([cell.textLabel.text isEqualToString:FONT_TABLE[i]]) {
                    _viewController.currentValueIndex = i;
                }
            }
            _viewController.tableData = valueData;
        } else if ([sectionTitle isEqualToString:TEXT_SCALE_SECTION]) {
            UITableViewCell *cell = sender;
            _viewController = [segue destinationViewController];
            NSMutableArray *valueData = [[NSMutableArray alloc] init];
            for (int i = 0; i < SIZE_OF_SCALE_TABLE; i++) {
                [valueData addObject:SCALE_TABLE[i]];
                if ([cell.textLabel.text isEqualToString:SCALE_TABLE[i]]) {
                    _viewController.currentValueIndex = i;
                }
            }
            _viewController.tableData = valueData;
        } else if ([sectionTitle isEqualToString:TEXT_UNDERLINE_SECTION]) {
            UITableViewCell *cell = sender;
            _viewController = [segue destinationViewController];
            NSMutableArray *valueData = [[NSMutableArray alloc] init];
            for (int i = 0; i < SIZE_OF_UNDERLINE_TABLE; i++) {
                [valueData addObject:UNDERLINE_TABLE[i]];
                if ([cell.textLabel.text isEqualToString:UNDERLINE_TABLE[i]]) {
                    _viewController.currentValueIndex = i;
                }
            }
            _viewController.tableData = valueData;
        } else if ([sectionTitle isEqualToString:TEXT_BOLD_SECTION]) {
            UITableViewCell *cell = sender;
            _viewController = [segue destinationViewController];
            NSMutableArray *valueData = [[NSMutableArray alloc] init];
            for (int i = 0; i < SIZE_OF_BOLD_TABLE; i++) {
                [valueData addObject:BOLD_TABLE[i]];
                if ([cell.textLabel.text isEqualToString:BOLD_TABLE[i]]) {
                    _viewController.currentValueIndex = i;
                }
            }
            _viewController.tableData = valueData;
        } else if ([sectionTitle isEqualToString:TEXT_REVERSE_SECTION]) {
            UITableViewCell *cell = sender;
            _viewController = [segue destinationViewController];
            NSMutableArray *valueData = [[NSMutableArray alloc] init];
            for (int i = 0; i < SIZE_OF_REVERSE_TABLE; i++) {
                [valueData addObject:REVERSE_TABLE[i]];
                if ([cell.textLabel.text isEqualToString:REVERSE_TABLE[i]]) {
                    _viewController.currentValueIndex = i;
                }
            }
            _viewController.tableData = valueData;
        } else if ([sectionTitle isEqualToString:TEXT_ROTATION_SECTION]) {
            UITableViewCell *cell = sender;
            _viewController = [segue destinationViewController];
            NSMutableArray *valueData = [[NSMutableArray alloc] init];
            for (int i = 0; i < SIZE_OF_ROTATIONE_TABLE; i++) {
                [valueData addObject:ROTATION_TABLE[i]];
                if ([cell.textLabel.text isEqualToString:ROTATION_TABLE[i]]) {
                    _viewController.currentValueIndex = i;
                }
            }
            _viewController.tableData = valueData;
        }
    }
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    if (0 <= indexPath.section && indexPath.section <= SIZE_OF_SECTION_TITLE_TABLE) {
        NSString *sectionTitle = SECTION_TITLE_TABLE[indexPath.section];
        if ([sectionTitle isEqualToString:TEXT_FONT_SECTION]) {
            return YES;
        } else if ([sectionTitle isEqualToString:TEXT_SCALE_SECTION]) {
            return YES;
        } else if ([sectionTitle isEqualToString:TEXT_UNDERLINE_SECTION]) {
            return YES;
        } else if ([sectionTitle isEqualToString:TEXT_BOLD_SECTION]) {
            return YES;
        } else if ([sectionTitle isEqualToString:TEXT_REVERSE_SECTION]) {
            return YES;
        } else if ([sectionTitle isEqualToString:TEXT_ROTATION_SECTION]) {
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}

#pragma mark - Button Action
- (IBAction)printButtonOnClicked:(id)sender {
    [self startLoadingView];
    dispatch_async([PrinterManager getDispatchQueue], ^{
        NSString *text = [ValueManager getCurrentStringValue:KEY_TYPE_TEXT];
        NSInteger font = [ValueManager convertFontStringToInt:[ValueManager getCurrentStringValue:KEY_TYPE_FONT]];
        NSInteger scale = [ValueManager convertScaleStringToInt:[ValueManager getCurrentStringValue:KEY_TYPE_SCALE]];
        NSInteger underline = [ValueManager convertUnderlineStringToInt:[ValueManager getCurrentStringValue:KEY_TYPE_UNDERLINE]];
        NSInteger bold = [ValueManager convertBoldStringToInt:[ValueManager getCurrentStringValue:KEY_TYPE_BOLD]];
        NSInteger reverse = [ValueManager convertReverseStringToInt:[ValueManager getCurrentStringValue:KEY_TYPE_REVERSE]];
        NSInteger rotation = [ValueManager convertRotationStringToInt:[ValueManager getCurrentStringValue:KEY_TYPE_ROTATION]];
        
        BOOL result = [PrinterManager printText:text font:font scale:scale underline:underline bold:bold reverse:reverse rotate:rotation];
        [self stopLoadingView];
        if (result == NO) {
            [self showMessageBox:@"" message:[NSString stringWithFormat:@"%@%@", @"Attempt to print text failed.\n ErrorCode : ", [PrinterManager getErrorCodeText]]];
        }
    });
}

- (IBAction)closeButtonOnClicked:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#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)setDefaultValue {
    if ([[ValueManager getCurrentStringValue:KEY_TYPE_FONT] length] == 0) {
        [[NSUserDefaults standardUserDefaults] setObject:@"ABC0123456789" forKey:KEY_TYPE_TEXT];
        [[NSUserDefaults standardUserDefaults] setObject:TEXT_FONT_A forKey:KEY_TYPE_FONT];
        [[NSUserDefaults standardUserDefaults] setObject:TEXT_SCALE_1 forKey:KEY_TYPE_SCALE];
        [[NSUserDefaults standardUserDefaults] setObject:TEXT_UNDERLINE_NONE forKey:KEY_TYPE_UNDERLINE];
        [[NSUserDefaults standardUserDefaults] setObject:TEXT_BOLD_OFF forKey:KEY_TYPE_BOLD];
        [[NSUserDefaults standardUserDefaults] setObject:TEXT_REVERSE_OFF forKey:KEY_TYPE_REVERSE];
        [[NSUserDefaults standardUserDefaults] setObject:TEXT_ROTATION_NONE forKey:KEY_TYPE_ROTATION];
    }
}

- (void)reloadTableView {
    if (0 < _sectionIndex && _sectionIndex < SIZE_OF_SECTION_TITLE_TABLE) {
        NSString *sectionTitle = SECTION_TITLE_TABLE[_sectionIndex];
        if ([sectionTitle isEqualToString:TEXT_FONT_SECTION]) {
            for (int i = 0; i < SIZE_OF_FONT_TABLE; i++) {
                if (_viewController.currentValueIndex == i) {
                    [ValueManager setCurrentStringValue:KEY_TYPE_FONT value:FONT_TABLE[i]];
                }
            }
        } else if ([sectionTitle isEqualToString:TEXT_SCALE_SECTION]) {
            for (int i = 0; i < SIZE_OF_SCALE_TABLE; i++) {
                if (_viewController.currentValueIndex == i) {
                    [ValueManager setCurrentStringValue:KEY_TYPE_SCALE value:SCALE_TABLE[i]];
                }
            }
        } else if ([sectionTitle isEqualToString:TEXT_UNDERLINE_SECTION]) {
            for (int i = 0; i < SIZE_OF_UNDERLINE_TABLE; i++) {
                if (_viewController.currentValueIndex == i) {
                    [ValueManager setCurrentStringValue:KEY_TYPE_UNDERLINE value:UNDERLINE_TABLE[i]];
                }
            }
        } else if ([sectionTitle isEqualToString:TEXT_BOLD_SECTION]) {
            for (int i = 0; i < SIZE_OF_BOLD_TABLE; i++) {
                if (_viewController.currentValueIndex == i) {
                    [ValueManager setCurrentStringValue:KEY_TYPE_BOLD value:BOLD_TABLE[i]];
                }
            }
        } else if ([sectionTitle isEqualToString:TEXT_REVERSE_SECTION]) {
            for (int i = 0; i < SIZE_OF_REVERSE_TABLE; i++) {
                if (_viewController.currentValueIndex == i) {
                    [ValueManager setCurrentStringValue:KEY_TYPE_REVERSE value:REVERSE_TABLE[i]];
                }
            }
        } else if ([sectionTitle isEqualToString:TEXT_ROTATION_SECTION]) {
            for (int i = 0; i < SIZE_OF_ROTATIONE_TABLE; i++) {
                if (_viewController.currentValueIndex == i) {
                    [ValueManager setCurrentStringValue:KEY_TYPE_ROTATION value:ROTATION_TABLE[i]];
                }
            }
        }
    }
    
    _sectionIndex = -1;
    [self.tableView reloadData];
}

- (void)reloadViewSize {
    _frameWidth = (NSInteger)self.view.bounds.size.width;    
    [self.tableView reloadData];
}

- (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];
    });
}

@end
