//
//  PrinterCallBackViewController.m
//  SIIMpaPrinterSample
//

#import "PrinterCallBackViewController.h"
#import "PrinterManager.h"
#import <SIIMpaPrinterManager/SIIMpaPrinterManager.h>
#import "ValueManager.h"

@interface  StatusElement : NSObject

@property NSString *text;
@property UIColor *textColor;

- (id)initWithTextAndColor:(NSString *)text textColor:(UIColor *)textColor;

@end

@implementation StatusElement

- (id)initWithTextAndColor:(NSString *)text textColor:(UIColor *)textColor {
    self = [super init];
    if (self) {
        self.text = text;
        self.textColor = textColor;
    }
    return self;
}

@end

@interface PrinterCallBackViewController () <UITableViewDelegate, UITableViewDataSource>

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

@end

@implementation PrinterCallBackViewController {
    StatusElement *_onlineStatus;
    StatusElement *_statusTable[12];
    dispatch_queue_t _gcd_printerStatus;
    UIView *_indicatorView;    
}

static NSUInteger const SIZE_OF_SECTION_TITLE_TABLE = 2;
static NSString *const SECTION_TITLE_TABLE[] = {
    CALLBACK_ONLINE_SECTION,
    CALLBACK_STATUS_SECTION
};

static NSUInteger const SIZE_OF_CALLBACK_STATUS_TABLE = 12;
static NSString *const CALLBACK_STATUS_TABLE[] = {
    CALLBACK_VOLTAGE_ERROR,
    CALLBACK_HARDWARE_ERROR,
    CALLBACK_HEAD_TEMPERATURE_ERROR,
    CALLBACK_OUT_OF_PAPER_ERROR,
    CALLBACK_PAPER_JAM_ERROR,
    CALLBACK_COVER_OPEN_ERROR,
    CALLBACK_BATTERY_ERROR,
    CALLBACK_FEED_SWTICH_STATE,
    CALLBACK_PAPER_FEED_STATE,
    CALLBACK_RETURN_WAITING_STATE,
    CALLBACK_FLASH_MEMORY_REWRITING,
    CALLBACK_BATTERY_STATE
};

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.delegate = (id <UITableViewDelegate>)self;
    self.tableView.dataSource = (id <UITableViewDataSource>)self;
    _gcd_printerStatus = dispatch_queue_create("com.sii-ps.printerStatus", DISPATCH_QUEUE_SERIAL);
    
    _onlineStatus = [[StatusElement alloc] initWithTextAndColor:@"-" textColor:[UIColor blackColor]];
    
    for (int i = 0; i < SIZE_OF_CALLBACK_STATUS_TABLE; i++) {
        _statusTable[i] = [[StatusElement alloc] initWithTextAndColor:@"-" textColor:[UIColor blackColor]];
    }
    
    [self initIndicatorView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self startLoadingView];
    dispatch_async([PrinterManager getDispatchQueue], ^{
        BOOL result = [PrinterManager startCallBack:self sel:@selector(StatusChanged:)];
        [self stopLoadingView];
        if (result == NO) {
            [self showMessageBox:@"" message:[NSString stringWithFormat:@"%@%@", @"Attempt to start callback failed.\n ErrorCode : ", [PrinterManager getErrorCodeText]]];
        }
    });
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self startLoadingView];
    dispatch_async([PrinterManager getDispatchQueue], ^{
        [PrinterManager stopCallBack];
        [self stopLoadingView];
    });
}

#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 {
    if (section < SIZE_OF_SECTION_TITLE_TABLE) {
        NSString *sectionTitle = SECTION_TITLE_TABLE[section];
        if ([sectionTitle isEqualToString:CALLBACK_ONLINE_SECTION]) {
            return 1;
        } else if ([sectionTitle isEqualToString:CALLBACK_STATUS_SECTION]) {
            return SIZE_OF_CALLBACK_STATUS_TABLE;
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    NSString *sectionTitle = SECTION_TITLE_TABLE[indexPath.section];
    UITableViewCell *cell;
    if ([sectionTitle isEqualToString:CALLBACK_ONLINE_SECTION]) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        cell.textLabel.text = _onlineStatus.text;
        cell.textLabel.textColor = _onlineStatus.textColor;
    } else if ([sectionTitle isEqualToString:CALLBACK_STATUS_SECTION]) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        cell.textLabel.text = CALLBACK_STATUS_TABLE[indexPath.row];
        cell.detailTextLabel.text = _statusTable[indexPath.row].text;
        cell.detailTextLabel.textColor = _statusTable[indexPath.row].textColor;
    }
    return cell;
}

#pragma mark - Button Action
- (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)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)StatusChanged:(SIIMpaPrinterStatus *)status {
    dispatch_async(_gcd_printerStatus, ^{
        if (status.errOffline) {
            self->_onlineStatus = [[StatusElement alloc] initWithTextAndColor:@"Offline" textColor:[UIColor redColor]];
            
            for (int i = 0; i < SIZE_OF_CALLBACK_STATUS_TABLE; i++) {
                self->_statusTable[i] = [[StatusElement alloc] initWithTextAndColor:@"-" textColor:[UIColor blackColor]];
            }
        } else {
            self->_onlineStatus = [[StatusElement alloc] initWithTextAndColor:@"Online" textColor:[UIColor greenColor]];
            
            if (status.errVoltage) {
                self->_statusTable[0] = [[StatusElement alloc] initWithTextAndColor:@"Err" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[0] = [[StatusElement alloc] initWithTextAndColor:@"NO" textColor:[UIColor blueColor]];
            }
            
            if (status.errHardware) {
                self->_statusTable[1] = [[StatusElement alloc] initWithTextAndColor:@"Err" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[1] = [[StatusElement alloc] initWithTextAndColor:@"NO" textColor:[UIColor blueColor]];
            }
            
            if (status.errHeadTemperature) {
                self->_statusTable[2] = [[StatusElement alloc] initWithTextAndColor:@"Err" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[2] = [[StatusElement alloc] initWithTextAndColor:@"NO" textColor:[UIColor blueColor]];
            }
            
            if (status.errOutOfPaper) {
                self->_statusTable[3] = [[StatusElement alloc] initWithTextAndColor:@"Err" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[3] = [[StatusElement alloc] initWithTextAndColor:@"NO" textColor:[UIColor blueColor]];
            }
            
            if (status.errMarkPaperJam) {
                self->_statusTable[4] = [[StatusElement alloc] initWithTextAndColor:@"Err" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[4] = [[StatusElement alloc] initWithTextAndColor:@"NO" textColor:[UIColor blueColor]];
            }
            
            if (status.errCoverOpen) {
                self->_statusTable[5] = [[StatusElement alloc] initWithTextAndColor:@"Err" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[5] = [[StatusElement alloc] initWithTextAndColor:@"NO" textColor:[UIColor blueColor]];
            }
            
            if (status.errBattery) {
                self->_statusTable[6] = [[StatusElement alloc] initWithTextAndColor:@"Err" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[6] = [[StatusElement alloc] initWithTextAndColor:@"NO" textColor:[UIColor blueColor]];
            }
            
            if (status.stateFeedSwitch) {
                self->_statusTable[7] = [[StatusElement alloc] initWithTextAndColor:@"ON" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[7] = [[StatusElement alloc] initWithTextAndColor:@"OFF" textColor:[UIColor blueColor]];
            }
            
            if (status.statePaperFeed) {
                self->_statusTable[8] = [[StatusElement alloc] initWithTextAndColor:@"Feeding" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[8] = [[StatusElement alloc] initWithTextAndColor:@"Stop" textColor:[UIColor blueColor]];
            }
            
            if (status.stateReturnWaiting) {
                self->_statusTable[9] = [[StatusElement alloc] initWithTextAndColor:@"Err" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[9] = [[StatusElement alloc] initWithTextAndColor:@"NO" textColor:[UIColor blueColor]];
            }
            
            if (status.stateFlashMemoryRewriting) {
                self->_statusTable[10] = [[StatusElement alloc] initWithTextAndColor:@"Writing" textColor:[UIColor redColor]];
            } else {
                self->_statusTable[10] = [[StatusElement alloc] initWithTextAndColor:@"NO" textColor:[UIColor blueColor]];
            }
            
            if ((long)status.stateBattery == 0){
                self->_statusTable[11] = [[StatusElement alloc] initWithTextAndColor:@"NONE" textColor:[UIColor blueColor]];
            } else if((long)status.stateBattery == 1){
                self->_statusTable[11] = [[StatusElement alloc] initWithTextAndColor:@"Lev4" textColor:[UIColor blueColor]];
            } else if((long)status.stateBattery == 2){
                self->_statusTable[11] = [[StatusElement alloc] initWithTextAndColor:@"Lev3" textColor:[UIColor blueColor]];
            } else if((long)status.stateBattery == 3){
                self->_statusTable[11] = [[StatusElement alloc] initWithTextAndColor:@"Lev2" textColor:[UIColor blueColor]];
            } else if((long)status.stateBattery == 4){
                self->_statusTable[11] = [[StatusElement alloc] initWithTextAndColor:@"Lev1" textColor:[UIColor blueColor]];
            } else {
                self->_statusTable[11] = [[StatusElement alloc] initWithTextAndColor:@"Err" textColor:[UIColor redColor]];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}

@end
