//
//  RAMorFlashImage.m
//  POSSDKForIOS 2013-07-31(2)
//
//  Created by liangchenying on 12-4-16.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "RAMorFlashImage.h"
#import "ButtonPullDownPrepare.h"
#import "ButtonPullDownRealize.h"

@interface RAMorFlashImage()
@property (nonatomic, retain) POSSDK	 *pos_sdk;
@end

@implementation RAMorFlashImage

@synthesize Cut;
@synthesize PrintImageButton;
@synthesize Back;
@synthesize RAMorFlashSelectButton;
@synthesize ImageName;
@synthesize FlashImageName;
@synthesize ImageWidth;
@synthesize RAMDownloadImageIDButton;
@synthesize RAMDownloadImageID;
@synthesize PrintImageID;
@synthesize ImagePrintModeButton;
@synthesize DownloadImageButton;

@synthesize pos_sdk	                   = _pos_sdk;

@synthesize array_RAMDownloadImageID   = _array_RAMDownloadImageID;
@synthesize array_ImagePrintMode       = _array_ImagePrintMode;

@synthesize selectedRAMDownloadImageID = _selectedRAMDownloadImageID;
@synthesize selectedImagePrintMode     = _selectedImagePrintMode;

- (NSMutableArray*)array_RAMDownloadImageID
{
    if(_array_RAMDownloadImageID  == nil)
    {
        _array_RAMDownloadImageID = [[NSMutableArray alloc] initWithCapacity:1024];
    }
    
    return _array_RAMDownloadImageID;
}

- (NSMutableArray*)array_ImagePrintMode
{
    if(_array_ImagePrintMode  == nil)
    {
        _array_ImagePrintMode = [[NSMutableArray alloc] initWithCapacity:1024];
    }
    
    return _array_ImagePrintMode;
}

- (id)initWithNibNamePOSSDK:(NSString *)nibNameOrNil pos_sdk:(POSSDK*)pos_sdk bundle:(NSBundle *)nibBundleOrNil
{
    self.pos_sdk = pos_sdk;
    return [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) 
    {
        //**************************************************************************************************
        //Add object for array_RAMDownloadImageID
        [self.array_RAMDownloadImageID addObject:@"0"];
        [self.array_RAMDownloadImageID addObject:@"1"];
        [self.array_RAMDownloadImageID addObject:@"2"];
        [self.array_RAMDownloadImageID addObject:@"3"];
        [self.array_RAMDownloadImageID addObject:@"4"];
        [self.array_RAMDownloadImageID addObject:@"5"];
        [self.array_RAMDownloadImageID addObject:@"6"];
        [self.array_RAMDownloadImageID addObject:@"7"];
        
        //**************************************************************************************************
        //Add object for array_ImagePrintMode
        [self.array_ImagePrintMode addObject:@"Normal Size"];
        [self.array_ImagePrintMode addObject:@"Double Width"];
        [self.array_ImagePrintMode addObject:@"Double Height"];
        [self.array_ImagePrintMode addObject:@"Quadruple"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.selectedRAMDownloadImageID = 1;
    self.selectedImagePrintMode     = 0;

    [self.ImageName                setDelegate:self];
    [self.FlashImageName           setDelegate:self];
    [self.ImageWidth               setDelegate:self];
    [self.PrintImageID             setDelegate:self];    
    [self.ImageName                setText:@"SAMPLE.bmp"];
    [self.FlashImageName           setText:@"SAMPLE.bmp,Jpg.jpg,face.PNG"];

    [self.ImageWidth               setText:@"500"];
    [self.PrintImageID             setText:@"1"];    
    [self.RAMDownloadImageIDButton setTitle:@"1" forState:UIControlStateNormal];
    [self.ImagePrintModeButton     setTitle:@"Normal Size" forState:UIControlStateNormal];
    
    //**************************************************************************************************
    //Draw position and size for controller(DownloadImageButton) 
	self.DownloadImageButton.frame   = CGRectMake(114,220,192,31);
    
    //**************************************************************************************************
    //Let "FlashImageName" enable to be used 
    ButtonEnableAndAlpha(self.FlashImageName, 0, 0);
}

- (void)viewDidUnload
{
    [self setBack:nil];
    [self setRAMorFlashSelectButton:nil];
    [self setImageName:nil];
    [self setImageWidth:nil];
    [self setRAMDownloadImageIDButton:nil];
    [self setPrintImageID:nil];
    [self setImagePrintModeButton:nil];
    [self setCut:nil];
    [self setDownloadImageButton:nil];
	[self setRAMDownloadImageID:nil];
    [self setFlashImageName:nil];
    [self setPrintImageButton:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//**************************************************************************************************
//Exit the keyboard by clicking "return"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"])
    {
        [self.ImageName      resignFirstResponder];
        [self.FlashImageName resignFirstResponder];
        [self.ImageWidth     resignFirstResponder];
        [self.PrintImageID   resignFirstResponder];

        return NO;
    } 
    return YES;
}

//**************************************************************************************************
//Choose RAM or Flash Image
- (IBAction)selectRAMorFlash:(id)sender 
{	
    //**************************************************************************************************
    //Choose RAM
    if ([self.RAMorFlashSelectButton selectedSegmentIndex] == 0)
    {
        //**************************************************************************************************
        //In the situation of choosing RAM,the position of DownloadImageButton would be adjusted
        self.DownloadImageButton.frame = CGRectMake(114,220,192,31);

        //**************************************************************************************************
        //Set controllers enable to be used or not,meanwhile set visual or not
        ButtonEnableAndAlpha(self.RAMDownloadImageIDButton, 1, 1);
        ButtonEnableAndAlpha(self.RAMDownloadImageID, 1, 1);
        ButtonEnableAndAlpha(self.FlashImageName, 0, 0);
        ButtonEnableAndAlpha(self.ImageName, 1, 1);
    }
    //**************************************************************************************************
    //Choose Flash
    else
    {
        //**************************************************************************************************
        //In the situation of choosing RAM,the position of DownloadImageButton\FlashImageName would be adjusted
        self.DownloadImageButton.frame = CGRectMake(114,173,192,31);
        self.FlashImageName.frame      = CGRectMake(114,84,192,31);
        
        //**************************************************************************************************
        //Set controllers enable to be used or not,meanwhile set visual or not
        ButtonEnableAndAlpha(self.RAMDownloadImageIDButton, 0, 0);
        ButtonEnableAndAlpha(self.RAMDownloadImageID, 0, 0);        
        ButtonEnableAndAlpha(self.ImageName, 0, 0);
        ButtonEnableAndAlpha(self.FlashImageName, 1, 1);
    }

}

//**************************************************************************************************
//Back to MainView
- (IBAction)Back:(id)sender 
{
     [self dismissViewControllerAnimated:YES completion:nil];
}

//**************************************************************************************************
//Download image to RAM or Flash
- (IBAction)DownloadImage:(id)sender 
{
    SInt32  error_code = SUCCESS;
    SInt32  width      = 0;
    SInt32  i          = 0;
    SInt32  index      = 0;
    SInt32  id_RAM     = 0;
	NSString *image_name_RAM   = nil;
	NSString *full_path_RAM    = nil;
	UIImage  *image_RAM        = nil;
	NSString *flash_image_name = nil;
	NSArray  *list             = nil;
	NSMutableArray *image_set  = nil;	
	NSString *full_path_Flash  = nil;
	UIImage  *image_Flash      = nil;

    
    //**********************************************************************************************
	//Image cannot be nil,
    JudgeParamNil(ImageName, @"Image Name == nil,Please input Image Name");
    JudgeParamNil(FlashImageName, @"Image Name == nil,Please input Image Name");
    
    //**********************************************************************************************
	//Printer width cannot be nil,
    JudgeParamNil(ImageWidth, @"PrinterWidth == nil,Please input Printer Width");
    
    //**********************************************************************************************
	//Judge printer width must be digits
    JudgeParamDigitOrNot(ImageWidth, @"ERROR Printer width! It must be   0  or 64-65535.");
    
    //**********************************************************************************************
	//Printer width must be 0 or 64-65535
    width = [self.ImageWidth.text intValue];
    JudgePrinterWidthRange(width,@"ERROR Printer width! It must be  0  or 64-65535.",65535);
    
    if ([self.RAMorFlashSelectButton selectedSegmentIndex] == 0)
    {
		
        //**************************************************************************************************
        //In the situation of choosing RAM, get image	
        image_name_RAM = ImageName.text;
        full_path_RAM  = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:image_name_RAM];
        image_RAM      = [[UIImage alloc] initWithContentsOfFile:full_path_RAM];
        
        if (image_RAM == nil) 
        {
            AlertViewShow(@"Image is not exist,please check image name.");
            goto ExitLine;
        }
        
        id_RAM = [[self.RAMDownloadImageIDButton currentTitle] intValue];
        //**************************************************************************************************
        //Download Image to RAM
		error_code = [self.pos_sdk  imageDownloadToPrinterRAM:id_RAM Image:image_RAM PrinterWidth:width];
		[image_RAM release];
		image_RAM = nil;
		
        //**************************************************************************************************
        //If Download Failed ,Show ERROR Message
		if (error_code == ERR_INVALID_ARGUMENT) 
		{
			AlertViewShow(@"ERROR Image Paramter!");
            goto ExitLine;
		}
        else if (error_code != SUCCESS)
        {
            AlertViewShow(@"ERROR TimeOut! Please reconnect Printer.");
            goto ExitLine;
        }
        
        //**************************************************************************************************
        //If Download success ,Show SUCCESS Message
        AlertViewShow(@"SUCCESS Download Image to RAM.");
    }
    else
    {
        //**************************************************************************************************
        //In the situation of choosing Flash.Every image separated by ','
        flash_image_name = FlashImageName.text;
        list = [flash_image_name componentsSeparatedByString:@","];
        image_set = [[NSMutableArray alloc] initWithCapacity:[list count]];
        
        //**************************************************************************************************
        //Get every image and add to image_set
        for(index = 0; index < [list count]; index++)
        {
            full_path_Flash = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[list objectAtIndex:index]];
            image_Flash     = [[UIImage alloc] initWithContentsOfFile:full_path_Flash];
            if (image_Flash == nil) 
            {
                AlertViewShow(@"Image is not exist,please check image name.");
                goto ExitLine;
            }
			
            [image_set addObject:image_Flash];
			[image_Flash release];
        }
        
        //**************************************************************************************************
        //Download the images to Flash
        error_code = [self.pos_sdk imageDownloadToPrinterFlash:image_set PrinterWidth:width];
        
        //**************************************************************************************************
        //If Download Failed ,Show ERROR Message
		if (error_code == ERR_INVALID_ARGUMENT) 
		{
			AlertViewShow(@"ERROR Image Paramter!");
            goto ExitLine;
		}
        else if (error_code != SUCCESS)
        {
            AlertViewShow(@"ERROR TimeOut! Please reconnect Printer.");
            goto ExitLine;
        }
        
        //**************************************************************************************************
        //If Download success ,Show SUCCESS Message
        AlertViewShow(@"SUCCESS Download Image to Flash.");
    }
    
ExitLine:	
	[image_set removeAllObjects];
	[image_set release];

    return;   
 }

//*************************************************************************************************
//Print Image downloaded to RAM or Flash
- (IBAction)PrintImage:(id)sender
{
    SInt32 error_code = SUCCESS;
    SInt32 print_ID   = 0;
    SInt32 i          = 0;
    SInt32 mode       = 0;
    
    //**************************************************************************************************
    //Print ID cannot be nil ,and must be Digit
    JudgeParamNil(PrintImageID, @"Print Image ID == nil.");
    JudgeParamDigitOrNot(PrintImageID, @"ERROR Print Image ID. It must be digit");
    //**************************************************************************************************
    //Print ID from PrintImageID
    print_ID = [self.PrintImageID.text intValue];
    
    if(self.selectedImagePrintMode == 0)          mode = NormalMode;
    else if(self.selectedImagePrintMode == 1)     mode = Double_width;
    else if(self.selectedImagePrintMode == 2)     mode = Double_height;
    else if(self.selectedImagePrintMode == 3)     mode = Quadruple;
    
    //**************************************************************************************************
    //In the situation of choosing RAM
    if ([self.RAMorFlashSelectButton selectedSegmentIndex] == 0)
    {
        //**********************************************************************************************
        //Judge the legitimacy of parameter
        if (print_ID < 0 || print_ID > 7) 
        {
            AlertViewShow(@"Print Image ID for RAM is ERROR.It must be 0-7");
            goto ExitLine;
        }
        
        //**********************************************************************************************
        //Printed image Downloaded to RAM
        error_code = [self.pos_sdk imageRAMPrint:print_ID Mode:mode];
    }
    else
    {
        //**************************************************************************************************
        //In the situation of choosing Flash,Judge the legitimacy of parameter
        if (print_ID < 1 || print_ID > 255) 
        {
            AlertViewShow(@"Print Image ID for Flash is ERROR.It must be 1-255");
            goto ExitLine;
        }
        
        //**********************************************************************************************
        //Printed image Downloaded to Flash
        error_code = [self.pos_sdk imageFlashPrint:print_ID Mode:mode];
    }
    
ExitLine:
    return;    
}

//**************************************************************************************************
//Get RAM Download Image ID Index
- (IBAction)selectRAMDownloadImageID:(id)sender
{
    PickerActionDoneButton done = ^(ButtonPullDownRealize *picker, NSInteger selectedIndex, id selectedValue)
    {
        self.selectedRAMDownloadImageID = selectedIndex;    
        [RAMDownloadImageIDButton setTitle:selectedValue forState:UIControlStateNormal];
    };
    
    PickerActionCancelButton cancel = ^(ButtonPullDownRealize *picker)
    {
    };
    
    [ButtonPullDownRealize sheetPickerTitle:@"RAM Download Image ID" Sheet:self.array_RAMDownloadImageID Selected:self.selectedRAMDownloadImageID DoneButton:done CancelButton:cancel Action:sender];
}

//**************************************************************************************************
//Get Print Mode Index
- (IBAction)selectPrintMode:(id)sender 
{
    PickerActionDoneButton done = ^(ButtonPullDownRealize *picker, NSInteger selectedIndex, id selectedValue)
    {
        self.selectedImagePrintMode = selectedIndex;    
        [ImagePrintModeButton setTitle:selectedValue forState:UIControlStateNormal];
    };
    
    PickerActionCancelButton cancel = ^(ButtonPullDownRealize *picker)
    {
    };
    
    [ButtonPullDownRealize sheetPickerTitle:@"Mode" Sheet:self.array_ImagePrintMode Selected:self.selectedImagePrintMode DoneButton:done CancelButton:cancel Action:sender];

}

//**************************************************************************************************
//Cut Paper
- (IBAction)Cut:(id)sender
{
    SInt32 error_code = SUCCESS;
    
    error_code = [self.pos_sdk systemCutPaper:CutPartAfterFeed FeedDistance:80];
    if (error_code != SUCCESS) 
    {
        AlertViewShow(@"ERROR TimeOut! Please reconnect Printer.");
    }
    
ExitLine:
    return;
}

- (void)dealloc 
{
    [self.Back release];
    [self.RAMorFlashSelectButton release];
    [self.ImageName release];
    [self.ImageWidth release];
    [self.RAMDownloadImageIDButton release];
    [self.PrintImageID release];
    [self.ImagePrintModeButton release];
    [self.array_RAMDownloadImageID release];
    [self.array_ImagePrintMode release];
    [self.Cut release];
    [self.DownloadImageButton release];
	[self.RAMDownloadImageID release];
    [self.FlashImageName release];

    [self.PrintImageButton release];
    [super dealloc];
}

@end
