
//
//  Created by Fabio Roberto Vitello on 12/03/12.
//  Copyright (c) 2012 nothing. All rights reserved.
//

//#import "CustomCellShowData.h"
#import "CustomCellView.h"
#import "ShowFieldViewController.h"

@implementation ShowFieldViewController

@synthesize dataSource;

-(id) initWithVbtId:(NSString *)id {
if(self = [super init]){
    
    dataSource = [[NSMutableDictionary alloc] init];

    
    vbtId=id;
    screenFrame = [[UIScreen mainScreen] bounds];
    
    
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(screenFrame.origin.x, 
                                                                screenFrame.origin.y, 
                                                                screenFrame.size.width, 
                                                                screenFrame.size.height)\
                                               style:UITableViewStyleGrouped];
    
    
    myTableView.delegate = self;
    myTableView.dataSource = self;
    
    
    [self setView:myTableView];

  
    
    NSString *par=[NSString stringWithFormat:@"vbtId=%@&op=vbt_field",vbtId];
    
    dbHelper=[[DbHelper alloc]initWithReference:@"http://visivoportal.oact.inaf.it/VisIVOSmart/db_query.php?db=vis"];
//    dbHelper=[[DbHelper alloc]initWithReference:@"http://visivo-server.oact.inaf.it/VisIVOSmart/db_query.php?db=vis"];
    dbHelper.delegate = self;
    dbHelper.delegateMethod = @selector(parseData:);
    dbHelper.delegateErrorMethod=@selector(parseError:);
    
    
    
    [dbHelper setPostParameter:par];
    dataArray = [[NSMutableArray alloc] init];



    field=@"";
    sel_row=-1;

	
    
    imageview= [[UIImageView alloc] initWithFrame:CGRectMake(0, 120,[UIScreen mainScreen].bounds.size.width,250)];
            
    [self.view addSubview:imageview];

}
return self;
}


-(void)createPicker
{
    // Calculate the screen's width.
    float screenWidth = [UIScreen mainScreen].bounds.size.width;
        
    // Init the picker view.
    pickerView = [[UIPickerView alloc] init];
    
    // Set the delegate and datasource. Don't expect picker view to work
    // correctly if you don't set it.
    [pickerView setDataSource: self];
    [pickerView setDelegate: self];
    
    [pickerView setFrame: CGRectMake(0, 40, screenWidth, 150)];
    
    // Before we add the picker view to our view, let's do a couple more
    // things. First, let the selection indicator (that line inside the
    // picker view that highlights your selection) to be shown.
    pickerView.showsSelectionIndicator = YES;
    
    // Allow us to pre-select the first option in the pickerView.
    [pickerView selectRow:0 inComponent:0 animated:YES];
    
    //Add the picker in our view.
    actionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                              delegate:nil
                                     cancelButtonTitle:nil
                                destructiveButtonTitle:nil
                                     otherButtonTitles:nil];
    
    [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    
    
    UISegmentedControl *doneButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Done"]];
    doneButton.momentary = YES; 
    doneButton.frame = CGRectMake(10, 7.0f, 50.0f, 30.0f);
    doneButton.segmentedControlStyle = UISegmentedControlStyleBar;
    doneButton.tintColor = [UIColor blueColor];
    [doneButton addTarget:self action:@selector(doneActionSheet:) forControlEvents:UIControlEventValueChanged];
    [actionSheet addSubview:doneButton];
    [doneButton release];
    
    
    UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];
    closeButton.momentary = YES; 
    closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
    closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    [closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
    [actionSheet addSubview:closeButton];
    [closeButton release];
    
    
    [actionSheet addSubview:pickerView];
    
    [pickerView release];
    
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    
    [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
	[actionSheet release];     
    
    
}

- (void)dismissActionSheet:(id)sender
{
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)doneActionSheet:(id)sender
{
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    
    if (sel_row!=-1)
    {
    
        alert=[[UIAlertView alloc] initWithTitle: NSLocalizedString(@"loading",@"") message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [alert show];
    
        float diff=screenFrame.size.width-alert.bounds.size.width;
    
        indicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        indicator.center =CGPointMake(screenFrame.size.width/2-diff/2,70);
        [indicator startAnimating];
        [alert addSubview:indicator];
        [indicator release];
    
        [self performSelectorInBackground:@selector(loadImageInBackground) withObject:nil];
        
    }

    
  
}

- (void) loadImageInBackground {
    
    
    
    NSString *urlAddress = [[allRows objectAtIndex:sel_row] objectForKey:@"Path"];
    urlAddress = [urlAddress stringByReplacingOccurrencesOfString:@"/VisIVOWeb/" withString:@"http://visivoportal.oact.inaf.it/VisIVOWeb/"];
   // urlAddress = [urlAddress stringByReplacingOccurrencesOfString:@"/VisIVOWeb/" withString:@"http://visivo-server.oact.inaf.it/VisIVOWeb/"];
    
	// Retrieve the remote image
	NSURL *imgURL = [NSURL URLWithString:urlAddress];
    
	NSData *imgData = [NSData dataWithContentsOfURL:imgURL];
	UIImage *img    = [[UIImage alloc] initWithData:imgData];
	
	// Image retrieved, call main thread method to update image, passing it the downloaded UIImage
	[self performSelectorOnMainThread:@selector(assignImage:) withObject:img waitUntilDone:YES];
    
}

- (void) assignImage:(UIImage *)img
{
    
    [imageview setImage:img]; 
    

    [myTableView reloadData];
    
    [alert dismissWithClickedButtonIndex:0 animated:YES];


}


#pragma mark -

//Metodo eseguito in caso di errore durante la connessione
-(void)parseError:(id)sender
{
    
	//Avviso l'utente che c'e' stato un errore durante la connessione al server
	UIActionSheet *errorActionSheet = [[UIActionSheet alloc] initWithTitle: NSLocalizedString(@"conn_error",@"") 
															 delegate:nil 
													cancelButtonTitle:@"OK" 
											   destructiveButtonTitle:nil 
													otherButtonTitles:nil]; 
	
	
	[errorActionSheet showInView:[[self view] window]];
	[errorActionSheet release];     
	
}


//Metodo eseguito se la connessione è terminata senza errori
-(void)parseData:(id)sender {
	
	DbHelper *tmpConnection = (DbHelper *)sender;
	
    [dataSource setDictionary:tmpConnection.receivedDictionary ];
    
    allRows = [dataSource objectForKey:@"results"];
    [dataArray addObject:@""];

    for(int i=0;i<[allRows count];i++)
    {
        NSMutableDictionary *tmpDataSource = [allRows objectAtIndex:i];
        [dataArray addObject:[tmpDataSource objectForKey:@"FieldName"]];
    }
    
}


#pragma mark -
#pragma mark Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString *CellIdentifier = @"Cell";
    
    CustomCellView *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[CustomCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier type:2] autorelease];
    }
    
    
    
    cell.primaryLabel.text = @"Field";
   
    cell.secondaryLabel.text=field;

    cell.myImageViewEnd.image = [UIImage imageNamed:@"arrowDown.png"];

    return cell;
}

// Number of components.
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// Total rows in our component.
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [dataArray count];
}

// Display each row's data.
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [dataArray objectAtIndex: row];
}

// Do something with the selected row.
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    
   field=[dataArray objectAtIndex: row];
   sel_row=row-1;
    
}


//Metodo eseguito quando l'utente clicca su un elemento della tabella
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    [self performSelector:@selector(selectField)];
    
    
}

-(void) selectField
{
   
    [self performSelector:@selector(createPicker)];

}


- (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.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end
