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

#import "CategoriesRadiosViewController.h"
#import "AppDelegate.h"

@interface CategoriesRadiosViewController ()

@end

@implementation CategoriesRadiosViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self.dataTable setSectionHeaderHeight:44.0f];
        [self displayBackView];
    }
    return self;
}

- (void)setCategory:(NSDictionary *)category {
    
    categoryDictionary = category;
}

- (void)setParentViewController:(UniversalViewController *)parent {
    
    parentVC = parent;
}

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

- (void)likeCategoryButtonPressed {
    
    [appDelegate likeCategory:categoryDictionary];
    [dataTable reloadData];
}

- (void)unlikeCategoryButtonPressed {
    
    [appDelegate unlikeCategory:categoryDictionary];
    [dataTable reloadData];
}

- (void)cityButtonPressed {
    
    [appDelegate.dataController parseCitiesWithCountry:[categoryDictionary objectForKey:@"id"]];
}

- (void)refreshWithCityData:(NSArray *)cityData {
    
    
    if (cityData != nil && cityData.count > 0) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                 delegate:self
                                                        cancelButtonTitle:@"Annuler"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:nil];
        for (int i=0; i<cityData.count; i++) {
            [actionSheet addButtonWithTitle:[[cityData objectAtIndex:i] objectForKey:@"title"]];
        }
        [actionSheet showInView:self.view];
    }
}


//-----------------------------------------
//		UIActionSheet Delegate
//-----------------------------------------

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex != actionSheet.cancelButtonIndex) {
        NSLog(@"CLICKED BUTTON AT INDEX : %d",buttonIndex);
        [appDelegate.cityRadiosVC refreshTableWithData:nil];
        [appDelegate.dataController parseRadiosWithCity:[actionSheet buttonTitleAtIndex:buttonIndex] fromCountry:[categoryDictionary objectForKey:@"id"]];
        [appDelegate.window setRootViewController:appDelegate.cityRadiosVC];
    }
}

//-----------------------------------------
//		IconDownloader Delegate
//-----------------------------------------

- (void)appImageDidLoad:(IconDownloader *)downloader {
    
    if (downloader.indexPathInTableView != nil && dataArray.count > downloader.indexPathInTableView.row) {
        [dataTable reloadRowsAtIndexPaths:[NSArray arrayWithObject:downloader.indexPathInTableView] withRowAnimation:UITableViewRowAnimationNone];
    }
}


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

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    [self.loadingTableView setFrame:CGRectMake((dataTable.frame.size.width - 240.0f)/2, dataTable.frame.origin.y + dataTable.sectionHeaderHeight + 60.0f, 240.0f, 60.0f)];
    [self.noResultTableLabel setFrame:CGRectMake(dataTable.frame.origin.x + 10.0f, dataTable.frame.origin.y + dataTable.sectionHeaderHeight + 60.0f, dataTable.frame.size.width - 20.0f, dataTable.rowHeight - 10.0f)];
    
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(5.0f, 0.0f, self.dataTable.frame.size.width - 10.0f, self.dataTable.sectionHeaderHeight)];
    header.backgroundColor = [UIColor colorWithRed:22.0f/255.0f green:145.0f/255.0f blue:189.0f/255.0f alpha:1.0f];
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(5.0f, 0.0f, header.frame.size.width - 10.0f, header.frame.size.height)];
    [title setTextAlignment:NSTextAlignmentCenter];
    [title setText:[[categoryDictionary objectForKey:@"title"] uppercaseString]];
    [title setFont:[UIFont systemFontOfSize:16]];
    [title setBackgroundColor:[UIColor clearColor]];
    [title setTextColor:[UIColor whiteColor]];
    [header addSubview:title];
    
    //categorie : par localisation
    if ([parentVC isEqual:appDelegate.categoriesVC] && appDelegate.categoriesVC.selectedFilterIndex == 1) {
        [title setFrame:CGRectMake(5.0f, 0.0f, header.frame.size.width - 50.0f, header.frame.size.height)];
        
        UIImageView *likeCategoryImage = [[UIImageView alloc] initWithFrame:CGRectMake(header.frame.size.width - 45.0f, (header.frame.size.height - 25.0f)/2, 25.0f, 25.0f)];
        [likeCategoryImage setContentMode:UIViewContentModeScaleAspectFit];
        [likeCategoryImage setClipsToBounds:YES];
        [header addSubview:likeCategoryImage];
        
        UIButton *likeCategoryButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [likeCategoryButton setFrame:likeCategoryImage.frame];
        [likeCategoryButton setShowsTouchWhenHighlighted:YES];
        [header addSubview:likeCategoryButton];
        
        if ([appDelegate.dataController isFavoriteCategoryWithId:[categoryDictionary objectForKey:@"id"]] == NO) {
            [likeCategoryButton removeTarget:self action:@selector(unlikeCategoryButtonPressed) forControlEvents:UIControlEventTouchUpInside];
            [likeCategoryButton addTarget:self action:@selector(likeCategoryButtonPressed) forControlEvents:UIControlEventTouchUpInside];
            [likeCategoryImage setImage:[UIImage imageNamed:@"likeRadio"]];
        } else {
            [likeCategoryButton removeTarget:self action:@selector(likeCategoryButtonPressed) forControlEvents:UIControlEventTouchUpInside];
            [likeCategoryButton addTarget:self action:@selector(unlikeCategoryButtonPressed) forControlEvents:UIControlEventTouchUpInside];
            [likeCategoryImage setImage:[UIImage imageNamed:@"likeRadioSelected"]];
        }
    }
    //autour du monde
    else if (currentTabIndex == 2) {
        [title setTextAlignment:NSTextAlignmentLeft];
        
        if (dataArray != nil && dataArray.count > 0) {
            [title setFrame:CGRectMake(5.0f, 0.0f, header.frame.size.width - 90.0f, header.frame.size.height)];
            
            UILabel *cityLabel = [[UILabel alloc]initWithFrame:header.frame];
            [cityLabel setTextAlignment:NSTextAlignmentRight];
            [cityLabel setText:@"Choisir une ville"];
            [cityLabel setFont:[UIFont systemFontOfSize:12]];
            [cityLabel setBackgroundColor:[UIColor clearColor]];
            [cityLabel setTextColor:[UIColor whiteColor]];
            [header addSubview:cityLabel];
            
            UIButton *cityButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [cityButton setFrame:cityLabel.frame];
            [cityButton addTarget:self action:@selector(cityButtonPressed) forControlEvents:UIControlEventTouchUpInside];
            [header addSubview:cityButton];
        }
    }
    return header;
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    int nbRowInSection = 0;
    if (dataArray != nil) {
        nbRowInSection = [dataArray count];
    }
    return nbRowInSection;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"dataCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    //if(cell == nil) {
    //NSLog(@"cell = nil");
    
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    
    UIView *background = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f , tableView.frame.size.width,tableView.rowHeight)];
    if (indexPath.row % 2) {
        background.backgroundColor = [UIColor colorWithRed:232.0f/255.0f green:243.0f/255.0f blue:248.0f/248.0f alpha:1.0f];
    } else {
        background.backgroundColor = [UIColor whiteColor];
    }
    [cell.contentView addSubview:background];
    
    UIImageView *radioLogoImage = [[UIImageView alloc]initWithFrame:CGRectMake(10.0f, 5.0f, tableView.rowHeight - 10.0f, tableView.rowHeight - 10.0f)];
    [radioLogoImage setContentMode:UIViewContentModeScaleAspectFit];
    [radioLogoImage setClipsToBounds:YES];
    UIView *defaultView = [[UIView alloc] initWithFrame:radioLogoImage.frame];
    defaultView.backgroundColor = [UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f];
    [cell.contentView addSubview:defaultView];
    [cell.contentView addSubview:radioLogoImage];
    
    if([iconDownloaderDictionary objectForKey:indexPath] == nil) {
        IconDownloader *iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.indexPathInTableView = indexPath;
        iconDownloader.delegate = self;
        [iconDownloaderDictionary setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownloadAtUrl:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"thumb"] withMaxSize:(tableView.rowHeight - 10.0f)*2];
    } else if ([[iconDownloaderDictionary objectForKey:indexPath] appIcon] != nil) {
        [radioLogoImage setImage:[[iconDownloaderDictionary objectForKey:indexPath] appIcon]];
        [defaultView removeFromSuperview];
    }
    
    UILabel *radioTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(radioLogoImage.frame.origin.x + radioLogoImage.frame.size.width + 10.0f, 10.0f, tableView.frame.size.width - radioLogoImage.frame.origin.x - radioLogoImage.frame.size.width - 40.0f, tableView.rowHeight - 20.0f)];
    [radioTitleLabel setText:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"title"]];
    [radioTitleLabel setFont:[UIFont systemFontOfSize:16]];
    [radioTitleLabel setNumberOfLines:0];
    [radioTitleLabel setBackgroundColor:[UIColor clearColor]];
    [radioTitleLabel setTextColor:[UIColor blackColor]];
    [cell.contentView addSubview:radioTitleLabel];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType  = UITableViewCellAccessoryDisclosureIndicator;
    cell.tag            = indexPath.row;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [appDelegate setOldVC:self];
    [appDelegate.playerVC setNavigationTitle:@"Catégories"];
    [self selectRadioAtIndex:[NSNumber numberWithInt:indexPath.row]];
}

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