//
//  DetailFileViewController.m
//  VisIVOMobile
//
//  Created by Fabio Vitello on 9/03/12.
//  Copyright 2012 nothing. All rights reserved.
//


#import "DetailFileViewController.h"
//#import "DetailCustomCell.h"
#import "CustomCellView.h"
#import "ShowPictureViewController.h"
#import "ShowTableViewController.h"
#import "VideoPlayerViewController.h"


@implementation DetailFileViewController

-(id) initWithRowId:(int )id andUserId:(NSString *)user andCat:(NSString *)cat  {
	if(self = [super init]){
        
        dataSource = [[NSMutableDictionary alloc] init];
        
        
        CGRect frame= [[UIScreen mainScreen]bounds];
        
        myTableView = [[UITableView alloc] initWithFrame:CGRectMake(frame.origin.x, 
                                                                    frame.origin.y, 
                                                                    frame.size.width, 
                                                                    frame.size.height)];
        
        myTableView.delegate = self;
        myTableView.dataSource = self;
        
       
        rowId=id;
        userId=user;
        
        NSString *par=[NSString stringWithFormat:@"user_id=%@&op=dtl_list&cat=%@",userId,cat];
        
        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];
        
        
        [self setView:myTableView];
        
        
        [self setTitle:cat];
        
        
		
	}
	return self;
}

#pragma mark -
#pragma mark UITableView delegate and dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
    NSArray *tmpArray = [dataSource objectForKey:@"results"];
	return [tmpArray count];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    //DetailCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    CustomCellView *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
       // cell = [[[DetailCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell = [[[CustomCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier type:1] autorelease];
    }
    
    allElements = [dataSource objectForKey:@"results"];
	
	tmpRow = [allElements objectAtIndex:indexPath.row];

    NSString *type=[tmpRow objectForKey:@"Type"];
    
    if([type intValue]==2)
    {
        cell.myImageView.image = [UIImage imageNamed:@"table.png"];
    }
    else if([type intValue]==3)
    {
        cell.myImageView.image = [UIImage imageNamed:@"volume.png"];
    } 
    else if([type intValue]==4)
    {
        cell.myImageView.image = [UIImage imageNamed:@"images.png"];
    }
    else if([type intValue]==5)
    {
        cell.myImageView.image = [UIImage imageNamed:@"video.png"];
    }

    cell.primaryLabel.text=[tmpRow objectForKey:@"Name"];
    cell.secondaryLabel.text=[tmpRow objectForKey:@"Description"];
    cell.myImageViewEnd.image = [UIImage imageNamed:@"arrow.png"];

    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSArray *allRows = [dataSource objectForKey:@"results"];
     
    NSMutableDictionary *tmpDataSource = [allRows objectAtIndex:indexPath.row];
        
    NSString *type=[tmpDataSource objectForKey:@"Type"];
    
    //Selected VBT Point (2) or VBT Volume (3)
    if([type intValue]==2 || [type intValue] == 3)
    {

        ShowTableViewController *showtableVC = [[ShowTableViewController alloc] initWithVbtId:[tmpDataSource objectForKey:@"Id"] andFileName:[tmpDataSource objectForKey:@"Name"] andFileType:[type intValue]];
        showtableVC.dataSource = tmpDataSource;
        
        [self.navigationController pushViewController:showtableVC animated:YES];
        [showtableVC release];

    }  
    //Selected Image
    else if([type intValue]==4)
    {
        
     ShowPictureViewController *showPictVC = [[ShowPictureViewController alloc] init];
     showPictVC.dataSource = tmpDataSource;
     
     [self.navigationController pushViewController:showPictVC animated:YES];
     [showPictVC release];
        
    }
    //Selected Video
    else if([type intValue]==5)
    {
        
        
//        NSString *movie=[NSString stringWithFormat:@"http://visivo-server.oact.inaf.it/%@",[tmpDataSource objectForKey:@"Path"]];
        NSString *movie=[NSString stringWithFormat:@"http://visivoportal.oact.inaf.it/%@",[tmpDataSource objectForKey:@"Path"]];
        
        // Play movie from URL
        NSURL *movieURL = [NSURL URLWithString:movie];
        
       VideoPlayerViewController* moviePlayer = [[[VideoPlayerViewController alloc] initWithURL:movieURL] autorelease];
        
        // Show the movie player
        [self presentModalViewController:moviePlayer animated:YES];
        
        // Prep and play the movie
        [moviePlayer readyPlayer];    
    
        
    }

    
}


// Delete VBT/image/movie
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{
    
	if (editingStyle == UITableViewCellEditingStyleDelete) {
		
        NSArray *allRows = [dataSource objectForKey:@"results"];
        
        NSMutableDictionary *tmpDataSource = [allRows objectAtIndex:indexPath.row];
        
        NSString *vbtId=[tmpDataSource objectForKey:@"Id"];

        alert=[[UIAlertView alloc] initWithTitle: NSLocalizedString(@"delete",@"") message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
		indicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
		indicator.center =CGPointMake(135,70);
		[indicator startAnimating];
		[alert addSubview:indicator];
		[indicator release];
		[alert show];
		
		//Delete selcted object from dictionary
		[[dataSource mutableArrayValueForKey:@"results"] removeObjectAtIndex:[indexPath row]];
        
		//Delete object from tableview
		[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

		//Delete from database
        NSString *par=[NSString stringWithFormat:@"op=del_file&vbtId=%@",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 setPostParameter:par];
        
        [alert dismissWithClickedButtonIndex:0 animated:YES];

        

	} 
}

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


-(void)parseData:(id)sender {
	
	DbHelper *tmpConnection = (DbHelper *)sender;
	
    [dataSource setDictionary:tmpConnection.receivedDictionary ];
    
    [myTableView reloadData];
    
}


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