//
//  SecondViewController.m
//  SIIMpaPrinterSample
//

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

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

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

@end

@implementation SecondViewController {
    ValueViewController *_viewController;
    NSInteger _sectionIndex;
    int _footerSize;
    NSInteger _frameWidth;    
}

static NSUInteger const SIZE_OF_SECTION_TITLE_TABLE = 7;
static NSString *const SECTION_TITLE_TABLE[] = {
    SETTINGS_GET_VERSIOM_SECTION,
    SETTINGS_SOCKET_KEEP_TIME_SECTION,
    SETTINGS_WRITE_TIMEOUT_SECTION,
    SETTINGS_RESPONSE_TIMEOUT_SECTION,
    SETTINGS_CODEPAGE_SECTION,
    SETTINGS_INTERNATIONAL_CHARACTER_SECTION,
    SETTINGS_LOG_FILE_SIZE_SECTION
};

static NSUInteger const SIZE_OF_CODEPAGE_TABLE = 18;
static NSString *const CODEPAGE_TABLE[] = {
    SETTINGS_CODEPAGE_437,
    SETTINGS_CODEPAGE_KATAKANA,
    SETTINGS_CODEPAGE_850,
    SETTINGS_CODEPAGE_860,
    SETTINGS_CODEPAGE_863,
    SETTINGS_CODEPAGE_865,
    SETTINGS_CODEPAGE_857,
    SETTINGS_CODEPAGE_737,
    SETTINGS_CODEPAGE_1252,
    SETTINGS_CODEPAGE_866,
    SETTINGS_CODEPAGE_852,
    SETTINGS_CODEPAGE_858,
    SETTINGS_CODEPAGE_855,
    SETTINGS_CODEPAGE_864,
    SETTINGS_CODEPAGE_1250,
    SETTINGS_CODEPAGE_1251,
    SETTINGS_CODEPAGE_1253,
    SETTINGS_CODEPAGE_1254
};

static NSUInteger const SIZE_OF_INTERNATIONAL_CHARACTER_TABLE = 14;
static NSString *const INTERNATIONAL_CHARACTER_TABLE[] = {
    SETTINGS_INTERNATIONAL_CHARACTER_USA,
    SETTINGS_INTERNATIONAL_CHARACTER_FRANCE,
    SETTINGS_INTERNATIONAL_CHARACTER_GERMANY,
    SETTINGS_INTERNATIONAL_CHARACTER_UNITED_KINGDOM,
    SETTINGS_INTERNATIONAL_CHARACTER_DENMARK_1,
    SETTINGS_INTERNATIONAL_CHARACTER_SWEDEN,
    SETTINGS_INTERNATIONAL_CHARACTER_ITALY,
    SETTINGS_INTERNATIONAL_CHARACTER_SPAIN_1,
    SETTINGS_INTERNATIONAL_CHARACTER_JAPAN,
    SETTINGS_INTERNATIONAL_CHARACTER_NORWAY,
    SETTINGS_INTERNATIONAL_CHARACTER_DENMARK_2,
    SETTINGS_INTERNATIONAL_CHARACTER_SPAIN_2,
    SETTINGS_INTERNATIONAL_CHARACTER_LATIN_AMERICA,
    SETTINGS_INTERNATIONAL_CHARACTER_ARABIA
};

static NSUInteger const SIZE_OF_LOG_FILE_SIZE_TABLE = 4;
static NSString *const LOG_FILE_SIZE_TABLE[] = {
    SETTINGS_LOG_FILE_SIZE_1M,
    SETTINGS_LOG_FILE_SIZE_5M,
    SETTINGS_LOG_FILE_SIZE_10M,
    SETTINGS_LOG_FILE_SIZE_50M,
};

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

-(void)viewDidDisappear:(BOOL)animated {
    [self removeKeyboardNotification];
    [super viewDidDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self addKeyboardNotification];
    [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:SETTINGS_SOCKET_KEEP_TIME_SECTION])
        || ([sectionTitle isEqualToString:SETTINGS_GET_VERSIOM_SECTION])
        || ([sectionTitle isEqualToString:SETTINGS_WRITE_TIMEOUT_SECTION])
        || ([sectionTitle isEqualToString:SETTINGS_RESPONSE_TIMEOUT_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];
        if ([sectionTitle isEqualToString:SETTINGS_SOCKET_KEEP_TIME_SECTION]) {
            textField.text = [ValueManager getCurrentStringValue:KEY_TYPE_SOCKET_KEEP_TIME];
        } else if ([sectionTitle isEqualToString:SETTINGS_GET_VERSIOM_SECTION]) {
            textField.text = [PrinterManager getVersion];
            textField.enabled = NO;
        } else if ([sectionTitle isEqualToString:SETTINGS_WRITE_TIMEOUT_SECTION]) {
            textField.text = [PrinterManager getWriteTimeout];
        } else if ([sectionTitle isEqualToString:SETTINGS_RESPONSE_TIMEOUT_SECTION]) {
            textField.text = [PrinterManager getResponseTimeout];
        }
        [cell.contentView addSubview:textField];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
    } else if ([sectionTitle isEqualToString:SETTINGS_CODEPAGE_SECTION]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = [PrinterManager getCodePage];
    } else if ([sectionTitle isEqualToString:SETTINGS_INTERNATIONAL_CHARACTER_SECTION]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = [PrinterManager getInternationalCharacter];
    } else if ([sectionTitle isEqualToString:SETTINGS_LOG_FILE_SIZE_SECTION]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if ([ValueManager getCurrentStringValue:KEY_TYPE_LOG_FILE_SIZE] == nil) {
            [ValueManager setCurrentStringValue:KEY_TYPE_LOG_FILE_SIZE value:LOG_FILE_SIZE_TABLE[3]];
        }
        cell.textLabel.text = [ValueManager getCurrentStringValue:KEY_TYPE_LOG_FILE_SIZE];
    }
    
    return cell;
}

#pragma mark - TextField
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if (0 <= textField.tag && textField.tag < SIZE_OF_SECTION_TITLE_TABLE) {
        NSString *sectionTitle = SECTION_TITLE_TABLE[textField.tag];
        if ([sectionTitle isEqualToString:SETTINGS_SOCKET_KEEP_TIME_SECTION]) {
            BOOL result = YES;
            if ([textField.text integerValue] < 60) {
                textField.text = @"60";
                result = NO;
            } else if ([textField.text integerValue] > 300) {
                textField.text = @"300";
                result = NO;
            }
            [ValueManager setCurrentStringValue:KEY_TYPE_SOCKET_KEEP_TIME value:textField.text];
            return result;
        } else if ([sectionTitle isEqualToString:SETTINGS_WRITE_TIMEOUT_SECTION]) {
            BOOL result = YES;
            if ([textField.text integerValue] < 1000) {
                textField.text = @"1000";
                result = NO;
            } else if ([textField.text integerValue] > 90000) {
                textField.text = @"90000";
                result = NO;
            }
            [PrinterManager setWriteTimeout:textField.text];
            return result;
        } else if ([sectionTitle isEqualToString:SETTINGS_RESPONSE_TIMEOUT_SECTION]) {
            BOOL result = YES;
            if ([textField.text integerValue] < 1000) {
                textField.text = @"1000";
                result = NO;
            } else if ([textField.text integerValue] > 90000) {
                textField.text = @"90000";
                result = NO;
            }
            [PrinterManager setResponseTimeout:textField.text];
            return result;
        }
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:string];
    if ([[NSCharacterSet decimalDigitCharacterSet] isSupersetOfSet:characterSet]) {
        NSMutableString *inputText= [textField.text mutableCopy];
        [inputText replaceCharactersInRange:range withString:string];
        return YES;
    } else {
        return NO;
    }
}

#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:SETTINGS_CODEPAGE_SECTION]) {
            UITableViewCell *cell = sender;
            _viewController = [segue destinationViewController];
            NSMutableArray *valueData = [[NSMutableArray alloc] init];
            for (int i = 0; i < SIZE_OF_CODEPAGE_TABLE; i++) {
                [valueData addObject:CODEPAGE_TABLE[i]];
                if ([cell.textLabel.text isEqualToString:CODEPAGE_TABLE[i]]) {
                    _viewController.currentValueIndex = i;
                }
            }
            _viewController.tableData = valueData;
        } else if ([sectionTitle isEqualToString:SETTINGS_INTERNATIONAL_CHARACTER_SECTION]) {
            UITableViewCell *cell = sender;
            _viewController = [segue destinationViewController];
            NSMutableArray *valueData = [[NSMutableArray alloc] init];
            for (int i = 0; i < SIZE_OF_INTERNATIONAL_CHARACTER_TABLE; i++) {
                [valueData addObject:INTERNATIONAL_CHARACTER_TABLE[i]];
                if ([cell.textLabel.text isEqualToString:INTERNATIONAL_CHARACTER_TABLE[i]]) {
                    _viewController.currentValueIndex = i;
                }
            }
            _viewController.tableData = valueData;
        } else if ([sectionTitle isEqualToString:SETTINGS_LOG_FILE_SIZE_SECTION]) {
            UITableViewCell *cell = sender;
            _viewController = [segue destinationViewController];
            NSMutableArray *valueData = [[NSMutableArray alloc] init];
            _viewController.currentValueIndex = 0;
            for (int i = 0; i < SIZE_OF_LOG_FILE_SIZE_TABLE; i++) {
                [valueData addObject:LOG_FILE_SIZE_TABLE[i]];
                if ([cell.textLabel.text isEqualToString:LOG_FILE_SIZE_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:SETTINGS_CODEPAGE_SECTION]) {
            return YES;
        } else if ([sectionTitle isEqualToString:SETTINGS_INTERNATIONAL_CHARACTER_SECTION]) {
            return YES;
        } else if ([sectionTitle isEqualToString:SETTINGS_LOG_FILE_SIZE_SECTION]) {
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}

#pragma mark - Private
- (void)setDefaultValue {
    if ([[ValueManager getCurrentStringValue:KEY_TYPE_SOCKET_KEEP_TIME] length] == 0) {
        [[NSUserDefaults standardUserDefaults] setObject:@"300" forKey:KEY_TYPE_SOCKET_KEEP_TIME];
    }
}

- (void)reloadTableView {
    if (0 <= _sectionIndex && _sectionIndex < SIZE_OF_SECTION_TITLE_TABLE) {
        NSString *sectionTitle = SECTION_TITLE_TABLE[_sectionIndex];
        if ([sectionTitle isEqualToString:SETTINGS_CODEPAGE_SECTION]) {
            for (int i = 0; i < SIZE_OF_CODEPAGE_TABLE; i++) {
                if (_viewController.currentValueIndex == i) {
                    [PrinterManager setCodePage:CODEPAGE_TABLE[i]];
                }
            }
        } else if ([sectionTitle isEqualToString:SETTINGS_INTERNATIONAL_CHARACTER_SECTION]) {
            for (int i = 0; i < SIZE_OF_INTERNATIONAL_CHARACTER_TABLE; i++) {
                if (_viewController.currentValueIndex == i) {
                    [PrinterManager setInternationalCharacter:INTERNATIONAL_CHARACTER_TABLE[i]];
                }
            }
        } else if ([sectionTitle isEqualToString:SETTINGS_LOG_FILE_SIZE_SECTION]) {
            for (int i = 0; i < SIZE_OF_LOG_FILE_SIZE_TABLE; i++) {
                if (_viewController.currentValueIndex == i) {
                    [PrinterManager setLogFileSize:LOG_FILE_SIZE_TABLE[i]];
                    [ValueManager setCurrentStringValue:KEY_TYPE_LOG_FILE_SIZE value:LOG_FILE_SIZE_TABLE[i]];
                }
            }
        }
    }
    _sectionIndex = -1;
    [self.tableView reloadData];
}

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

- (void)addKeyboardNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    _footerSize = self.tableView.superview.frame.size.height - self.tableView.frame.size.height;
}

- (void)removeKeyboardNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)aNotification {
    CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    float keyboardHeight = keyboardRect.size.height;
    self.tableView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, (self.tableView.superview.frame.size.height - keyboardHeight));
}

- (void)keyboardWillHide:(NSNotification *)aNotification {
    self.tableView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.superview.frame.size.height - _footerSize);
}

@end
