//
//  AllzicViewController.m
//  Allzic
//
//  Created by Alia Bourouis on 24/03/14.
//  Copyright (c) 2014 Alia Bourouis. All rights reserved.
//

#import "AllzicViewController.h"
#import "AppDelegate.h"

@interface AllzicViewController ()

@end

@implementation AllzicViewController

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.title = self.screenName = @"allzic";
    
    /*
    NSMutableDictionary *event;
    event = [[GAIDictionaryBuilder createEventWithCategory:@"UI"
                                                    action:@"navigation"
                                                     label:@"allzic"
                                                     value:nil] build];
    [[GAI sharedInstance].defaultTracker send:event];
    [[GAI sharedInstance] dispatch];
    */
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self.view setBackgroundColor:[UIColor whiteColor]];
        [navigationTitle setText:@""];
        [navigationView addSubview:navTitleImage];
        [dataTable setShowsVerticalScrollIndicator:NO];
        infiniteDataArray = [[NSMutableArray alloc] init];
        radioLogoDictionary = [[NSMutableDictionary alloc] init];
        [self displayBackView];
    }
    return self;
}

- (void)addInfiniteData {
    
    //nombre actuel de lignes dans la table
    int nbRowsInfiniteNow = [dataTable numberOfRowsInSection:0];
    [infiniteDataArray addObjectsFromArray:dataArray];
    
    //nombre futur de lignes dans la table
    int nbRowsInfiniteAfter = infiniteDataArray.count / 4;
    if ((nbRowsInfiniteAfter * 4) < infiniteDataArray.count) {
        nbRowsInfiniteAfter++;
    }
    
    NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init];
    for (int i = nbRowsInfiniteNow; i < nbRowsInfiniteAfter; i++) {
        [indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:0]];
    }
    [dataTable beginUpdates];
    [dataTable insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationAutomatic];
    [dataTable endUpdates];
}

- (void)loadImage:(UIImageView *)imageView {
    
    NSString *url = [[infiniteDataArray objectAtIndex:imageView.tag] objectForKey:@"thumb"];
    if ([radioLogoDictionary objectForKey:url] == nil) {
        UIImage *loadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
        [radioLogoDictionary setObject:loadedImage forKey:url];
        [imageView setImage:loadedImage];
    } else {
        [imageView setImage:[radioLogoDictionary objectForKey:url]];
    }
}

- (void)backToParentView {
    
    [appDelegate.window setRootViewController:appDelegate.introVC];
}

//-----------------------------------------
//		ScrollView Delegate
//-----------------------------------------

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	
    if (infiniteDataArray != nil && infiniteDataArray.count > 0) {
        NSArray *paths = [dataTable indexPathsForVisibleRows];
        //nombre total de lignes dans la table
        int nbRowsInfinite = infiniteDataArray.count / 4;
        if ((nbRowsInfinite * 4) < infiniteDataArray.count) {
            nbRowsInfinite++;
        }
        //nombre de lignes pour afficher les radios allzic une seule fois
        int nbRows = dataArray.count / 4;
        if ((nbRows * 4) < dataArray.count) {
            nbRows++;
        }
        //si la ligne affichée fait partie de la dernière liste de radios, on en ajoute une et on recharge la tableview
        if ([[paths objectAtIndex:0] row] > (nbRowsInfinite - nbRows)) {
            [self addInfiniteData];
        }
    }
}


//-----------------------------------------
//		TableView Delegate
//-----------------------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (infiniteDataArray.count == 0 && dataArray != nil && dataArray.count > 0) {
        [infiniteDataArray addObjectsFromArray:dataArray];
    }
    int nbSection = 1;
    return nbSection;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    int nbRowInSection = 0;
    if (infiniteDataArray != nil) {
        nbRowInSection = (infiniteDataArray.count) / 4;
        if ((nbRowInSection * 4) < infiniteDataArray.count) {
            nbRowInSection++;
        }
    }
    return nbRowInSection;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"dataCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    //if(cell == nil) {
    
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        CGFloat margin = 10.0f;
        CGFloat pictureWidth = (appDelegate.screenBounds.size.width - (5 * margin)) / 4;
        CGFloat rowHeight = (pictureWidth * 1.67) + margin;
        
        UIView *background = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, tableView.frame.size.width, rowHeight)];
        
        if (indexPath.row == ([tableView numberOfRowsInSection:0] - 1)) {
            [background setFrame:CGRectMake(0.0f, 0.0f, tableView.frame.size.width, rowHeight + margin)];
        }
        background.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:background];
        
        UIImageView *radioLogoImage1 = [[UIImageView alloc]initWithFrame:CGRectMake(margin, 0.0f, pictureWidth, pictureWidth * 1.67)];
        [radioLogoImage1 setContentMode:UIViewContentModeScaleAspectFit];
        [radioLogoImage1 setClipsToBounds:YES];
        UIView *defaultView1 = [[UIView alloc] initWithFrame:radioLogoImage1.frame];
        defaultView1.backgroundColor = [UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f];
        [cell.contentView addSubview:defaultView1];
        [cell.contentView addSubview:radioLogoImage1];
        
        
        [radioLogoImage1 setTag:(indexPath.row * 4)];
        [self performSelectorInBackground:@selector(loadImage:) withObject:radioLogoImage1];
        
        UIButton *radioButton1 = [[UIButton alloc]initWithFrame:radioLogoImage1.frame];
        [radioButton1 setTag:((indexPath.row * 4) % dataArray.count)];
        [radioButton1 setShowsTouchWhenHighlighted:YES];
        [radioButton1 addTarget:self action:@selector(selectRadioAtIndex:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:radioButton1];
        
        if (infiniteDataArray.count > ((indexPath.row * 4) + 1)) {
            UIImageView *radioLogoImage2 = [[UIImageView alloc]initWithFrame:CGRectMake(margin * 2 + pictureWidth, 0.0f, pictureWidth, pictureWidth * 1.67)];
            [radioLogoImage2 setContentMode:UIViewContentModeScaleAspectFit];
            [radioLogoImage2 setClipsToBounds:YES];
            UIView *defaultView2 = [[UIView alloc] initWithFrame:radioLogoImage2.frame];
            defaultView2.backgroundColor = [UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f];
            [cell.contentView addSubview:defaultView2];
            [cell.contentView addSubview:radioLogoImage2];
            
            [radioLogoImage2 setTag:((indexPath.row * 4) + 1)];
            [self performSelectorInBackground:@selector(loadImage:) withObject:radioLogoImage2];
            
            UIButton *radioButton2 = [[UIButton alloc]initWithFrame:radioLogoImage2.frame];
            [radioButton2 setTag:(((indexPath.row * 4) + 1) % dataArray.count)];
            [radioButton2 setShowsTouchWhenHighlighted:YES];
            [radioButton2 addTarget:self action:@selector(selectRadioAtIndex:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:radioButton2];
        }
        
        if (infiniteDataArray.count > ((indexPath.row * 4) + 2)) {
            UIImageView *radioLogoImage3 = [[UIImageView alloc]initWithFrame:CGRectMake(margin * 3 + pictureWidth * 2, 0.0f, pictureWidth, pictureWidth * 1.67)];
            [radioLogoImage3 setContentMode:UIViewContentModeScaleAspectFit];
            [radioLogoImage3 setClipsToBounds:YES];
            UIView *defaultView3 = [[UIView alloc] initWithFrame:radioLogoImage3.frame];
            defaultView3.backgroundColor = [UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f];
            [cell.contentView addSubview:defaultView3];
            [cell.contentView addSubview:radioLogoImage3];
            
            [radioLogoImage3 setTag:((indexPath.row * 4) + 2)];
            [self performSelectorInBackground:@selector(loadImage:) withObject:radioLogoImage3];
            
            UIButton *radioButton3 = [[UIButton alloc]initWithFrame:radioLogoImage3.frame];
            [radioButton3 setTag:(((indexPath.row * 4) + 2) % dataArray.count)];
            [radioButton3 setShowsTouchWhenHighlighted:YES];
            [radioButton3 addTarget:self action:@selector(selectRadioAtIndex:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:radioButton3];
        }
        
        if (infiniteDataArray.count > ((indexPath.row * 4) + 3)) {
            UIImageView *radioLogoImage4 = [[UIImageView alloc]initWithFrame:CGRectMake(margin * 4 + pictureWidth * 3, 0.0f, pictureWidth, pictureWidth * 1.67)];
            [radioLogoImage4 setContentMode:UIViewContentModeScaleAspectFit];
            [radioLogoImage4 setClipsToBounds:YES];
            UIView *defaultView4 = [[UIView alloc] initWithFrame:radioLogoImage4.frame];
            defaultView4.backgroundColor = [UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f];
            [cell.contentView addSubview:defaultView4];
            [cell.contentView addSubview:radioLogoImage4];
            
            [radioLogoImage4 setTag:((indexPath.row * 4) + 3)];
            [self performSelectorInBackground:@selector(loadImage:) withObject:radioLogoImage4];
            
            UIButton *radioButton4 = [[UIButton alloc]initWithFrame:radioLogoImage4.frame];
            [radioButton4 setTag:(((indexPath.row * 4) + 3) % dataArray.count)];
            [radioButton4 setShowsTouchWhenHighlighted:YES];
            [radioButton4 addTarget:self action:@selector(selectRadioAtIndex:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:radioButton4];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //}
    return cell;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat margin = 10.0f;
    CGFloat pictureWidth = (appDelegate.screenBounds.size.width - (5 * margin)) / 4;
    CGFloat heightForRow = (pictureWidth * 1.67) + margin;
    
    int nbRows = (dataArray.count) / 4;
    if ((nbRows * 4) < dataArray.count) {
        nbRows++;
    }
    if (indexPath.row == (nbRows - 1)) {
        heightForRow += margin;
    }
    return heightForRow;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

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

@end
