//
//  HighScoreViewController.m
//  FinalProject
//
//  Created by Sean Campbell on 12/10/13.
//  Copyright (c) 2013 Sean Campbell. All rights reserved.
//

#import "HighScoreViewController.h"
#import "HighScoreSymbolViewController.h"
#import "HighScore.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@implementation HighScoreViewController

@synthesize managedObjectContext;

- (id) init
{
    if (self = [super init]) {
        self.navigationItem.title = @"High Scores";
        
        UIBarButtonItem *clearButtonItem = [[UIBarButtonItem alloc] init];
        clearButtonItem.title = @"Clear";
        clearButtonItem.target = self;
        clearButtonItem.action = @selector(clear);
        self.navigationItem.rightBarButtonItem = clearButtonItem;
        clearButtonItem = nil;
    }
    return self;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // Send a request to the database.
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"HighScores" inManagedObjectContext:managedObjectContext];
    request.entity = entity;
    request.predicate = [NSPredicate predicateWithFormat:@"symbol like \"*Set*\""];
    // Sort by score.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"symbol" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
    request.sortDescriptors = sortDescriptors;
    // Store high scores from the database into the high scores array.
    NSError *error = nil;
    highScores = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    // Clean up memory.
    request = nil;
    sortDescriptor = nil;
    sortDescriptors = nil;
    
    [self.tableView reloadData];
}

- (void) clear
{
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"Clear" message:@"Are you sure you want to clear all high scores? You cannot undo this action." delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
    [dialog show];
    dialog = nil;
}

- (void) displayHighScoreDetailsForButton: (UIView *)view
{
    // Display a dialog with detailed information about the high score.
    HighScore *score = [highScores objectAtIndex:view.tag];
    NSString *highScoreDetails = [NSString stringWithFormat:@"Date drawn: %@\nTime to draw symbol: %.2fs\nAccuracy: %d\nFinal score: %.2f", [score.date descriptionWithLocale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]], [score.timeElapsed doubleValue], [score.accuracy intValue], [score.score doubleValue]];
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:score.symbol message:highScoreDetails delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [dialog show];
    dialog = nil;
}

- (void) alertView: (UIAlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex
{
    if (buttonIndex != 0) {
        // Get everything from the database.
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"HighScores" inManagedObjectContext:managedObjectContext];
        request.entity = entity;
        // Store high scores from the database into the high scores array.
        NSError *error = nil;
        NSArray *allScores = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
        // Clean up memory.
        request = nil;

        for (HighScore *score in allScores) {
            // Don't delete the symbol sets themselves.
            if (score.symbolSet != nil)
                [managedObjectContext deleteObject: score];
            else {
                score.timeElapsed = 0;
                score.score = 0;
                score.accuracy = 0;
                score.date = [NSDate date];
            }
        }
        for (HighScore *score in highScores) {
            // Don't delete the symbol sets themselves.
            if (score.symbolSet != nil)
                [highScores removeObject:score];
        }
        [managedObjectContext save:&error];
        allScores = nil;
        [self.tableView reloadData];
    }
}

#pragma mark Table view methods

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

- (NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) section
{
    return highScores.count;
}

- (BOOL) tableView: (UITableView *) tableView canEditRowAtIndexPath: (NSIndexPath *) indexPath
{
    return NO;
}


- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
    if (cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    HighScore *highScore = [highScores objectAtIndex:indexPath.row];
    // Setup the text for the cell to display.
    cell.textLabel.text = [NSString stringWithFormat:@"%@   %.2f", highScore.symbol, [highScore.score doubleValue]];
    cell.textLabel.font = [UIFont fontWithName:@"Arial" size:14];
    highScore = nil;

    // Create info button that, when clicked, shows extra information about scoring on this set.
    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
    infoButton.center = CGPointMake(SCREEN_WIDTH - infoButton.bounds.size.width, cell.bounds.size.height / 2);
    infoButton.tag = indexPath.row;
    [infoButton setTitle:@"Info" forState:UIControlStateNormal];
    [infoButton addTarget:self action:@selector(displayHighScoreDetailsForButton:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:infoButton];

    return cell;

}

- (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath
{
    HighScoreSymbolViewController *symbolCtrl = [[HighScoreSymbolViewController alloc] init];
    symbolCtrl.managedObjectContext = self.managedObjectContext;
    symbolCtrl.symbolSet = [[highScores objectAtIndex:indexPath.row] symbol];
    [self.navigationController pushViewController:symbolCtrl animated:YES];
}

@end
