//
//  CEDevicesViewController.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 "CEDevicesViewController.h"
#import "CEFirstViewController.h"
#import <QuartzCore/QuartzCore.h>

#define DEVMASKBT   0x10
#define DEVMASKWIFI 0x20

@interface CEDevicesViewController () <UITableViewDataSource, UITableViewDelegate>

@end

@implementation CEDevicesViewController

@synthesize btDevicesArray;
@synthesize wifiDevicesArray;
@synthesize tableBTDevices;
@synthesize tableWIFIDevices;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Devices", @"Devices");
    }
    return self;
}
							
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    iDeviceSelected = -1;
    
    //Set Table Color (tableBTDevices)
    [tableBTDevices.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
    [tableBTDevices.layer setBorderColor: [[UIColor grayColor] CGColor]];
    [tableBTDevices.layer setBorderWidth: 1.0];
    [tableBTDevices.layer setCornerRadius:8.0f];
    [tableBTDevices.layer setMasksToBounds:YES];
    
    //Set Table Color (tableWIFIDevices)
    [tableWIFIDevices.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
    [tableWIFIDevices.layer setBorderColor: [[UIColor grayColor] CGColor]];
    [tableWIFIDevices.layer setBorderWidth: 1.0];
    [tableWIFIDevices.layer setCornerRadius:8.0f];
    [tableWIFIDevices.layer setMasksToBounds:YES];
    
    //Force Refresh(1st time)
    [self ButtonRefreshDevicesTouchDown:nil];
}

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

- (void)dealloc {
}
- (void)viewDidUnload {
    btDevicesArray = nil;
    tableBTDevices = nil;
    tableWIFIDevices = nil;
    btnRefreshDevices = nil;
    [super viewDidUnload];
}
- (IBAction)ButtonRefreshDevicesTouchDown:(id)sender
{
    NSError *error;
    iDeviceSelected = -1;    
    
    CEFirstViewController* mainView = [CEFirstViewController getInstance];
    
    //Close Device if is open
    if (mainView.currentCustomPrn != nil)
    {
        [mainView.currentCustomPrn Close:&error];
        mainView.currentCustomPrn = nil;
    }
    
    //Create Windows and Show it
    msg = [CEFirstViewController CreateOverMessage:@"Search Devices..."];
    [msg show];
    
    //Clear Tables
    btDevicesArray = nil;
    [tableBTDevices reloadData];
    wifiDevicesArray = nil;
    [tableWIFIDevices reloadData];
    
    //Get BT devices
    NSArray* tmpBTDevicesArray = [mainView.customiOsApi EnumBTDevices:&error];
    if (tmpBTDevicesArray != nil)
    {
        //Create the EMPTY list
        btDevicesArray = [[NSMutableArray alloc] initWithCapacity:0];
        EAAccessory *tmpAccess;
        
        //Write Description
        for(int i=0;i<[tmpBTDevicesArray count];i++)
        {
            //get the device
            tmpAccess = [tmpBTDevicesArray objectAtIndex:i];
            //Add to the table
            [btDevicesArray addObject:tmpAccess];
        }
        
        [tableBTDevices reloadData];
    }
    
    //Get ETH/ WIFI Devices (1000 ms of search)
    NSArray* tmpWIFIDevicesArray = [mainView.customiOsApi EnumWifiDevices:1000 :&error];
    if (tmpWIFIDevicesArray != nil)
    {
        //Create the EMPTY list
        wifiDevicesArray = [[NSMutableArray alloc] initWithCapacity:0];
        NSString* tmpString;
        
        //Write Description
        for(int i=0;i<[tmpWIFIDevicesArray count];i++)
        {
            //get the device
            tmpString = [tmpWIFIDevicesArray objectAtIndex:i];
            //Add to the table
            [wifiDevicesArray addObject:tmpString];
        }
        
        [tableWIFIDevices reloadData];
    }
    
    [msg dismissWithClickedButtonIndex:0 animated:YES];
    msg=nil;
}

//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
{
    if ([tableView isEqual:tableBTDevices])
        return [btDevicesArray count];
    
    if ([tableView isEqual:tableWIFIDevices])
        return [wifiDevicesArray count];
    
    return 0;
}

// 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];
    }
    
    if ([tableView isEqual:tableBTDevices])
    {
        NSString *eaAccessoryName = [NSString stringWithFormat:@"%@ (%@)",                                     [[btDevicesArray objectAtIndex:row] name], [[btDevicesArray objectAtIndex:row] serialNumber]];
        // Configure the cell... 
        cell.textLabel.text = eaAccessoryName;
        cell.imageView.image = nil;
        //If a device is selected
        if ((iDeviceSelected != -1) && (iDeviceSelected & DEVMASKBT))
        {
            //If is this the Device selected,
            if ((iDeviceSelected & 0x0F) == row)
            {
                cell.imageView.image = [UIImage imageNamed:@"ball.png"];
            }
        }
    }    
    else if ([tableView isEqual:tableWIFIDevices])
    {
        NSString *strDeviceIP = [NSString stringWithFormat:@"%@",                                     [wifiDevicesArray objectAtIndex:row]];
        // Configure the cell...
        cell.textLabel.text = strDeviceIP;
        cell.imageView.image = nil;
        //If a device is selected
        if ((iDeviceSelected != -1) && (iDeviceSelected & DEVMASKWIFI))
        {
            //If is this the Device selected,
            if ((iDeviceSelected & 0x0F) == row)
            {
                cell.imageView.image = [UIImage imageNamed:@"ball.png"];
            }
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSError *error;
    CEFirstViewController* mainView = [CEFirstViewController getInstance];

    
    iDeviceSelected = -1;
    
    //Close Device if is open
    if (mainView.currentCustomPrn != nil)
    {
        [mainView.currentCustomPrn Close:&error];
        mainView.currentCustomPrn = nil;
    }
    
    [tableBTDevices reloadData];
    [tableWIFIDevices reloadData];
    
    //Create Windows and Show it
    msg = [CEFirstViewController CreateOverMessage:@"Opening Device..."];
    [msg show];
    
    NSUInteger row = [indexPath row];
    
    if ([tableView isEqual:tableBTDevices])
    {
        //Unselect all the Wifi Devices
        for (NSIndexPath *indexPath in tableWIFIDevices.indexPathsForSelectedRows) {
            [tableWIFIDevices deselectRowAtIndexPath:indexPath animated:NO];
        }
        
        //Open BT Device
        mainView.currentCustomPrn = [mainView.customiOsApi GetPrinterDriverBT:[btDevicesArray objectAtIndex:row] :&error];
        
        [msg dismissWithClickedButtonIndex:0 animated:YES];
        msg=nil;
    }
    else if ([tableView isEqual:tableWIFIDevices])
    {
        //Unselect all the BT Devices
        for (NSIndexPath *indexPath in tableBTDevices.indexPathsForSelectedRows) {
            [tableBTDevices deselectRowAtIndexPath:indexPath animated:NO];
        }
        
        //Open WIFI Device
        mainView.currentCustomPrn = [mainView.customiOsApi GetPrinterDriverWIFI:[wifiDevicesArray  objectAtIndex:row] :&error];
        
        [msg dismissWithClickedButtonIndex:0 animated:YES];
        msg=nil;

    }
    
    if ((mainView.currentCustomPrn == nil) || error != nil)
    {
        NSString* stralertMsg = [NSString stringWithFormat:@"Open Device Error (%@)",
                                 [error localizedDescription]];
        
        UIAlertView *alerMsg = [[UIAlertView alloc] initWithTitle:@"Error..." message:stralertMsg delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alerMsg show];alerMsg = nil;
        mainView.currentCustomPrn = nil;
    }
    else
    {
        iDeviceSelected = (row & 0x0F);
        if ([tableView isEqual:tableBTDevices])
            iDeviceSelected |= DEVMASKBT;
        else if ([tableView isEqual:tableWIFIDevices])
            iDeviceSelected |= DEVMASKWIFI;
        
        NSString* stralertMsg = [NSString stringWithFormat:@"Succesfully Open Device\n%@\nFW Release %@",
                                 [mainView.currentCustomPrn GetPrinterName], [mainView.currentCustomPrn GetFirmwareVersion:&error]];
        
        UIAlertView *alerMsg = [[UIAlertView alloc] initWithTitle:@"" message:stralertMsg delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alerMsg show];alerMsg = nil;
    }
    
    [tableBTDevices reloadData];
    [tableWIFIDevices reloadData];
}

//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;
    }
    else
        iDeviceSelected = -1;
    
    
    [tableBTDevices reloadData];
    [tableWIFIDevices reloadData];
}


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

@end
