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

#import "CEFirstViewController.h"
#import "CEPrintViewController.h"
#import "CustomNSUtils.h"

@interface CEFirstViewController () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>


@end

@implementation CEFirstViewController


UIAlertView * loadingMsg;
UIAlertView * deleteAlert;
UIAlertView * deleteAllAlert;
NSString * loadingMsgStr;
int loadingRetCode;


@synthesize projectsArray;
@synthesize tableProjects;
@synthesize customXmliOsApi;
@synthesize paramsArray;
@synthesize currentCustomPrn;
@synthesize customiOsApi;
@synthesize antialiasText;
@synthesize antialiasShape;


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

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
#if 0
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *filepathz, *filenamez, *destinationPath;
    NSError *error=nil;
    

    filenamez = @"CustomXmlPrintIOS.zip";
    filepathz = [[NSBundle mainBundle] pathForResource:@"CustomXmlPrintIOS" ofType:@"zip"];
    destinationPath = [documentsDirectory stringByAppendingPathComponent:filenamez];
    [[NSFileManager defaultManager] copyItemAtPath:filepathz toPath:destinationPath error:&error];
    
    
    filenamez = @"CustomXmlPrintFlight.zip";
    filepathz = [[NSBundle mainBundle] pathForResource:@"CustomXmlPrintFlight" ofType:@"zip"];
    destinationPath = [documentsDirectory stringByAppendingPathComponent:filenamez];
    [[NSFileManager defaultManager] copyItemAtPath:filepathz toPath:destinationPath error:&error];
#endif
    
    customXmliOsApi = nil;
    customXmliOsApi = [[CustomXmliOSApi alloc] init];
    customiOsApi = [[CustomiOSApi alloc] init];
    instance = self;
    paramsArray = nil;
    iProjectSelected=-1;
    selectedProjectName=nil;
    lastOpenedProjectName = nil;
    currentCustomPrn = nil;
    antialiasText = nil;
    antialiasShape = nil;
    loadingMsgStr = nil;
    
    
    
    //Set Table Color (tableBTDevices)
    [tableProjects.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
    [tableProjects.layer setBorderColor: [[UIColor grayColor] CGColor]];
    [tableProjects.layer setBorderWidth: 1.0];
    [tableProjects.layer setCornerRadius:8.0f];
    [tableProjects.layer setMasksToBounds:YES];
    
    projectsArray = nil;
    //projectsArray = [[NSMutableArray alloc] initWithObjects:@"pippo", @"pluto", @"pippo", @"pluto",@"pippo", @"pluto",@"pippo", @"pluto",@"pippo", @"pluto",@"pippo", @"pluto",@"pippo", @"pluto",@"pippo", @"pluto",@"pippo", @"pluto",nil];
    
    //Force Refresh(1st time)
    //customXmliOsApi = nil;
    [self RefreshProjects:nil];

    //[self ButtonRefreshProjectsTouchDown:nil];

}

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

+ (UIAlertView*) CreateOverMessage:(NSString*)strTitle
{
    UIAlertView* av=[[UIAlertView alloc] initWithTitle:strTitle message:@"" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    UIActivityIndicatorView * ActInd=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [ActInd startAnimating];
    [ActInd setFrame:CGRectMake(110, 60, 37, 37)];
    [av addSubview:ActInd];
    
    return av;
}


- (IBAction)RefreshProjects:(id)sender
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
	NSString  *filepath, *filename, *projectName;
    
    BOOL isDir = false;
    	//printf("FONT DIR: %s\n", fontdirstr.toLatin1().data() );
	[[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory isDirectory:&isDir];
    
    projectsArray = [[ NSMutableArray alloc]initWithCapacity:0];
    
	if ( isDir )
	{
        
        NSError * error = nil;
		NSArray * list = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];
		for (int i = 0; i < list.count; ++i)
		{
            
			//filename = fileInfo.fileName();
			//filepath = fileInfo.filePath();
            filename = [list objectAtIndex:i];
            if ( [[filename lowercaseString] endsWith:@".zip"])
            {
                filepath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,filename];
                projectName = [filename substringToIndex:(filename.length-4)];
                [projectsArray addObject:projectName];
                
            }
        }
    }
    
    iProjectSelected=-1;
    selectedProjectName=nil;
    [tableProjects reloadData];
    
    CESecondViewController *paramController = [CESecondViewController getInstance];
    if ( paramController != nil)
    {
        paramController.paramsArray = [[NSMutableArray alloc] initWithCapacity:0];
        //[paramController.tableParams reloadData];
        //paramController.textParam.text=@"";
        [paramController reloadUI];
        
 
    }
    
    CEPrintViewController *printController = [CEPrintViewController getInstance];
    if ( printController != nil)
    {
        [printController resetUI];
        
    }
     
}

- (IBAction)ButtonRefreshProjectsTouchDown:(id)sender
{

    loadingMsg = [CEFirstViewController CreateOverMessage:@"Refreshing..."];
    [loadingMsg show];
    
    customXmliOsApi = nil;
    [self RefreshProjects:sender];
    
    [loadingMsg dismissWithClickedButtonIndex:0 animated:YES];
    loadingMsg=nil;

}

- (IBAction)ButtonDeleteProjectsTouchDown:(id)sender
{
    NSString * strmessage;
    if ( selectedProjectName != nil)
    {
        strmessage = @"Sure to delete selected project?";
        deleteAlert= [[UIAlertView alloc] initWithTitle:@"" message:strmessage delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:@"No", nil];
        [deleteAlert show];
    }
    else
    {
        strmessage = @"No project selected";
        UIAlertView *alerMsg = [[UIAlertView alloc] initWithTitle:@"" message:strmessage delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alerMsg show];
        alerMsg = nil;
    }

    //[deleteAlert release];
}
- (IBAction)ButtonDeleteAllProjectsTouchDown:(id)sender
{
    NSString * strmessage;
    
   strmessage = @"Sure to delete all projects?";
   deleteAllAlert= [[UIAlertView alloc] initWithTitle:@"" message:strmessage delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:@"No", nil];
   [deleteAllAlert show];
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if ([alertView isEqual:deleteAlert])
    {
        if ( selectedProjectName != nil)
        {
            if ( buttonIndex == 0)
            {
                NSError *error=nil;
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
                NSString *filenamez = [NSString stringWithFormat:@"%@.zip", selectedProjectName];
                NSString * filepathz = [documentsDirectory stringByAppendingPathComponent:filenamez];
                if ([[NSFileManager defaultManager] fileExistsAtPath:filepathz])
                    [[NSFileManager defaultManager] removeItemAtPath:filepathz error:&error];
                
                customXmliOsApi = nil;
                [self RefreshProjects:nil];

            }
            else
            {
                
            }
        }
        deleteAlert=nil;
    }
    else if ([alertView isEqual:deleteAllAlert])
    {
        if ( buttonIndex == 0)
        {
            
            NSError * error = nil;
            NSString *filename;
            NSString * filepath;
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
            NSArray * list = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];
            for (int i = 0; i < list.count; ++i)
            {
                
                //filename = fileInfo.fileName();
                //filepath = fileInfo.filePath();
                filename = [list objectAtIndex:i];
                if ( [[filename lowercaseString] endsWith:@".zip"])
                {
                    filepath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,filename];
                    if ([[NSFileManager defaultManager] fileExistsAtPath:filepath])
                        [[NSFileManager defaultManager] removeItemAtPath:filepath error:&error];
                    
                }
            }
            
            customXmliOsApi = nil;
            [self RefreshProjects:nil];
            
        }
        else
        {
            
        }
        deleteAllAlert=nil;
    }
}

- (IBAction)ButtonLoadProjectsTouchDown:(id)sender
{
   
    NSString * strmessage;
    BOOL doLoad = false;
    int bindex=0;


    if ( selectedProjectName != nil)
    {
        //strmessage = [NSString stringWithFormat:@"Project %@\nloaded succesfully",selectedProjectName];
        doLoad  = true;
    }
    else
    {
        strmessage = @"No project selected";
        doLoad = false;
    }
    
    if ( (lastOpenedProjectName != nil) && ([lastOpenedProjectName isEqualToString:selectedProjectName]))
    {
            
    }
    
    if ( doLoad )
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
        NSString *filenamez = [NSString stringWithFormat:@"%@.zip", selectedProjectName];
        NSString * filepathz = [documentsDirectory stringByAppendingPathComponent:filenamez];
        
        if ( customXmliOsApi != nil)
            customXmliOsApi = nil;
        
        antialiasText=nil;
        antialiasShape=nil;
        
        customXmliOsApi = [[CustomXmliOSApi alloc] init];
    

        loadingMsgStr = nil;
        loadingMsg =[[UIAlertView alloc] initWithTitle:@"Loading Project..." message:@"" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        UIActivityIndicatorView * ActInd=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [ActInd startAnimating];
        [ActInd setFrame:CGRectMake(110, 60, 37, 37)];
        [loadingMsg addSubview:ActInd];
        [loadingMsg setMessage:@"Please wait"];
        [loadingMsg show];
        loadingRetCode = -1;
        loadingMsgStr = @"";

        

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^ {
            //backgroung processing
            
            NSError * error = nil;;
            loadingRetCode = [customXmliOsApi SetXmlZipFilePath:filepathz :@"Custom" :true error:&error];
            error = nil;
            


                
            
                if ( loadingRetCode == 0)
                {
                    NSString * info = [ customXmliOsApi GetXmlParsingErrors:&error];
                    
                    if ( (info!= nil) && (info.length>0))
                        loadingMsgStr = [NSString stringWithFormat:@"Project %@\nloading SUCCESS\nInfo: %@",selectedProjectName, info];
                    else
                        loadingMsgStr = [NSString stringWithFormat:@"Project %@\nloading SUCCESS", selectedProjectName];

                    antialiasText = [ customXmliOsApi GetXmlObjectTag:@"Canvas1.antialiasText" error:&error];
                    antialiasShape = [ customXmliOsApi GetXmlObjectTag:@"Canvas1.antialiasShape" error:&error];
                    if ( antialiasText == nil)
                        antialiasText = @"2";
                    if ( antialiasShape == nil)
                        antialiasShape = @"0";
                    
                }
                else
                {
                    if ( (error != nil) && (error.description!= nil) )
                        loadingMsgStr = [NSString stringWithFormat:@"Project %@\nloading ERROR\nInfo: %@",selectedProjectName, error.description];
                    else
                        loadingMsgStr = [NSString stringWithFormat:@"Project %@\nloading ERROR",selectedProjectName];
                }
            
            
            
                dispatch_async( dispatch_get_main_queue(), ^ {
                //update UI
                    
                    
                        if ( loadingRetCode == 0)
                        {
                            NSError * error;
                            CESecondViewController *paramController = [CESecondViewController getInstance];
                            paramsArray = [customXmliOsApi GetXmlTagValListFromParamFile:nil error:&error];
                            if ( paramController != nil)
                            {
                                paramController.paramsArray = [NSMutableArray arrayWithArray:paramsArray];
                                [paramController reloadUI];
                            }
                            
                            CEPrintViewController *printController = [CEPrintViewController getInstance];
                            if ( printController != nil)
                            {
                                [printController resetUI];
                                
                            }
                            
                        }
                    
                    
                        [loadingMsg dismissWithClickedButtonIndex:bindex animated:YES];
                        loadingMsg=nil;
                    
                        if ( loadingMsgStr != nil)
                        {
                            loadingMsg = [[UIAlertView alloc] init];
                            [loadingMsg setTitle:@""];
                            [loadingMsg setDelegate:nil];
                            [loadingMsg setCancelButtonIndex:[loadingMsg addButtonWithTitle:@"OK"]];
                            [loadingMsg setMessage:loadingMsgStr];
                            [loadingMsg show];
                        }
                    
                    

                    
                   });
            
            
        });


    
    }
    else
    {
        
        UIAlertView *alerMsg = [[UIAlertView alloc] initWithTitle:@"" message:strmessage delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alerMsg show];
        alerMsg = 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:tableProjects])
        return [projectsArray 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:tableProjects])
    {
        //NSString *eaAccessoryName = [NSString stringWithFormat:@"%@ (%@)",                                     [[projectsArray objectAtIndex:row] name], [[projectsArray objectAtIndex:row] serialNumber]];
        NSString *prjname = [projectsArray objectAtIndex:row];
        
        // Configure the cell...
        cell.textLabel.text = prjname;
        cell.imageView.image = nil;
        
        
        
        if ( iProjectSelected != -1 )
        {
            //If a device is selected
            if (iProjectSelected == row)
            {
                cell.imageView.image = [UIImage imageNamed:@"ball.png"];
            }
        }

    }

    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    //CEFirstViewController* mainView = [CEFirstViewController getInstance];
    
   // [tableProjects reloadData];
    
    
    NSUInteger row = [indexPath row];
    
    if ([tableView isEqual:tableProjects])
    {
        iProjectSelected = row;
        selectedProjectName = [projectsArray objectAtIndex:row];
    }

    [tableProjects reloadData];
    
}



@end
