//
//  CEDeviceViewController.m
//  DemoCustomXmliOSApi
//
//  Created by sviluppo on 27/03/14.
//  Copyright (c) 2014 CUSTOM. All rights reserved.
//

#import "CEDeviceViewController.h"
#import "CEFirstViewController.h"

@interface CEDeviceViewController () <UITableViewDataSource, UITableViewDelegate>

@end

@implementation CEDeviceViewController




@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;
}











/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
