//
//  CEPrinterStatusViewController.m
//  DemoCustomiOSApi
//
//  Created by CUSTOM S.p.A. on 19/07/13.
//  Copyright (c) 2013 CUSTOM S.p.A.. All rights reserved.
//
//************************************************************************************
//*                                                                                  *
//* This document contains programming examples.                                     *
//*                                                                                  *
//* CUSTOM S.p.A. grants you a nonexclusive copyright license to use                 *
//* all programming code examples from which you can generate similar                *
//* function tailored to your own specific needs.                                    *
//*                                                                                  *
//* All sample code is provided by CUSTOM S.p.A. for illustrative purposes           *
//* only. These examples have not been thoroughly tested under all conditions.       *
//* CUSTOM S.p.A., therefore, cannot guarantee or imply reliability,                 *
//* serviceability, or function of these programs.                                   *
//*                                                                                  *
//* In no event shall CUSTOM S.p.A. be liable for any direct, indirect,              *
//* incidental, special, exemplary, or consequential damages (including, but not     *
//* limited to, procurement of substitute goods or services; loss of use, data,      *
//* or profits; or business interruption) however caused and on any theory of        *
//* liability, whether in contract, strict liability, or tort (including negligence  *
//* or otherwise) arising in any way out of the use of this software, even if        *
//* advised of the possibility of such damage.                                       *
//*                                                                                  *
//* All programs contained herein are provided to you "as is" without any            *
//* warranties of any kind.                                                          *
//* The implied warranties of non-infringement, merchantability and fitness for a    *
//* particular purpose are expressly disclaimed.                                     *
//*                                                                                  *
//************************************************************************************

#import "CEPrinterStatusViewController.h"
#import "CEFirstViewController.h"

@interface CEPrinterStatusViewController () <UITableViewDataSource, UITableViewDelegate>

@end

@implementation CEPrinterStatusViewController

@synthesize statusTxtArray;
@synthesize statusValueArray;
@synthesize tableStatus;

Boolean getStatusThreadRunning;

static CEPrinterStatusViewController *instance =nil;
+(CEPrinterStatusViewController *)getInstance
{
    return instance;
}

static bool bVisible =false;
+(void)SetVisible:(bool)visible
{
    bVisible =visible;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    instance = self;
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Status", @"Status");
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //Init Table
    statusTxtArray = [[NSMutableArray alloc] initWithCapacity:0];
    statusValueArray = [[NSMutableData alloc] initWithCapacity:0];
    
    Byte bApp[1];bApp[0] = 0;
    
    //Add Elements:
    NSString *str = @"No Paper";
    [statusTxtArray addObject:str];
    [statusValueArray appendBytes:bApp length:1];
    str = @"Near Paper End";
    [statusTxtArray addObject:str];
    [statusValueArray appendBytes:bApp length:1];
    str = @"Paper Rolling";
    [statusTxtArray addObject:str];
    [statusValueArray appendBytes:bApp length:1];
    str = @"No Head / Cover";
    [statusTxtArray addObject:str];
    [statusValueArray appendBytes:bApp length:1];
    str = @"LF Key Pressed";
    [statusTxtArray addObject:str];
    [statusValueArray appendBytes:bApp length:1];
    str = @"FF Key Pressed";
    [statusTxtArray addObject:str];
    [statusValueArray appendBytes:bApp length:1];    
    
    //Start Get Status Thread
    getStatusThreadRunning = true;
    [self performSelector:@selector(GetStatusThread) withObject:nil afterDelay:0.5];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    getStatusThreadRunning = false;
}

//Called every time is activated
- (void) viewWillAppear:(BOOL)animated
{
    Boolean printerConnected = false;
    float alpha = 0.5;
    
    CEFirstViewController* mainView = [CEFirstViewController getInstance];
    
    if (mainView.currentCustomPrn != nil)
    {
        //Enabled
        printerConnected = true;
        //100% colors
        alpha = 1.0;
    }
    
    //Enable / disable Objects
    tableStatus.alpha = alpha;    
}

- (BOOL)isVisible {
    return [self isViewLoaded] && self.view.window;
}

//Set the number of sections into the table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

// Set the number of lines for the table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [statusValueArray length];
}

// Set Cell Text
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSUInteger row = [indexPath row];
	static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell;
    
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Configure the cell...
    cell.textLabel.text = [statusTxtArray objectAtIndex:row];
    
    @synchronized(statusValueArray)
    {
        Byte* bStatusBuffer =(UInt8 *)statusValueArray.bytes;
        if (bStatusBuffer[row] == 0)
            cell.imageView.image = [UIImage imageNamed:@"ballG.png"];
        else
            cell.imageView.image = [UIImage imageNamed:@"ballR.png"];
    }
    
    return cell;
}

- (void) GetStatusThread
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^ {
        
        CustomPrinterStatus* stsPrn;
        CEFirstViewController* mainView = [CEFirstViewController getInstance];
        while (getStatusThreadRunning)
        {
            //sleep
            sleep(1);
            
            stsPrn = nil;

            //Only if is visible
            if (bVisible && (mainView.currentCustomPrn != nil))
            {
                NSError *error;
                //Get Status
                stsPrn = [mainView.currentCustomPrn GetPrinterFullStatus:&error];

                if (stsPrn != nil)
                {
                    
                    @synchronized(statusValueArray)
                    {
                        Byte* bStatusBuffer =(UInt8 *)statusValueArray.bytes;
                        
                        //No Paper
                        bStatusBuffer[0] = [stsPrn StsNOPAPER];
                        //Near Paper End
                        bStatusBuffer[1] = [stsPrn StsNEARENDPAP];
                        //Paper Rolling
                        bStatusBuffer[2] = [stsPrn StsPAPERROLLING];
                        //No Head / Cover
                        bStatusBuffer[3] = [stsPrn StsNOHEAD] | [stsPrn StsNOCOVER];
                        //LF Pressed
                        bStatusBuffer[4] = [stsPrn StsLFPRESSED];
                        //FF Pressed
                        bStatusBuffer[5] = [stsPrn StsFFPRESSED];
                    }
                    
                    //Refresh view
                    dispatch_async(dispatch_get_main_queue(),^{
                        [tableStatus reloadData];
                    });
                }
            }
  
        }
    });
    
}

@end
