#import "ReminderController.h"
#import "Reminder.h"

@implementation ReminderController

- (void)addReminder:(id)sender
{
    [self addReminder:sender atIndex:-1];
}

- (BOOL)addReminder:(id)sender atIndex:(int)rowIndex
{
    Reminder *aReminder;
    SEL aSelector;
    int hr, min, sec;
    BOOL repeats, shouldEmitSound, shouldShowAlertPanel, relative;

    aSelector  = @selector(reminderDue:);
    aReminder  = [[Reminder alloc] init];
    repeats    = (BOOL) [[repeatOnOffMatrix selectedCell] tag];
    relative   = (BOOL) [[absoluteRelativeMatrix selectedCell] tag];
    shouldEmitSound = (BOOL) [[soundOnOffMatrix selectedCell] tag];
    shouldShowAlertPanel = (BOOL) [[panelOnOffMatrix selectedCell] tag];
    hr  = [hoursField intValue];
    min = [minutesField intValue];
    sec = [secondsField intValue];

    if(relative == 0 || hr != 0 || min != 0 || sec != 0)
      {
        [aReminder setReminder:hr :min :sec :self :aSelector :(BOOL)repeats :(BOOL)relative :(BOOL)shouldEmitSound :(BOOL)shouldShowAlertPanel :[reminderMessageField stringValue]];
        if(rowIndex > -1)
          {
            [reminderArray insertObject:aReminder atIndex:rowIndex];
            [remindersTable selectRow:rowIndex byExtendingSelection:NO];
          }
        else
          {
            [reminderArray addObject:aReminder];
            [remindersTable selectRow:[reminderArray count]-1 byExtendingSelection:NO];
          }

        [remindersTable reloadData];
        return YES;
      }
    else
      {
        NSBeep();
        NSRunAlertPanel(@"EggTimer Warning",@"Relative Delay time must be greater than zero!", @"OK", nil, nil);
        return NO;
      }
}

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
    SEL clickSelector, timerSelector;
    NSImage *miniwindowImage;

    clickSelector = @selector(updateControls);
    timerSelector = @selector(reloadData);

    miniwindowImage = [[NSImage alloc] initWithContentsOfFile:@"MiniTimer.tiff"];
    [mainWindow setMiniwindowImage:miniwindowImage];

    reminderArray = [[NSMutableArray alloc] init];
    [remindersTable setDataSource:self];
    [remindersTable setAction:clickSelector];
    [[remindersTable tableColumnWithIdentifier:@"expired"] setDataCell:[NSImageCell new]];
    [[remindersTable tableColumnWithIdentifier:@"absolute_relative"] setDataCell:[NSImageCell new]];
    [[remindersTable tableColumnWithIdentifier:@"once_repeats"] setDataCell:[NSImageCell new]];
    [[remindersTable tableColumnWithIdentifier:@"sound"] setDataCell:[NSImageCell new]];
    [[remindersTable tableColumnWithIdentifier:@"alert_panel"] setDataCell:[NSImageCell new]];

    [remindersTable sizeLastColumnToFit];

    [timeField setRefusesFirstResponder:YES];

    [absoluteRelativeMatrix setRefusesFirstResponder:YES];
    [repeatOnOffMatrix setRefusesFirstResponder:YES];
    [soundOnOffMatrix setRefusesFirstResponder:YES];
    [panelOnOffMatrix setRefusesFirstResponder:YES];

    [absoluteRelativeMatrix selectCell:[absoluteRelativeMatrix cellWithTag:0]];

    [repeatOnOffMatrix selectCell:[repeatOnOffMatrix cellWithTag:0]];
    [[repeatOnOffMatrix cellWithTag:1] setEnabled:NO];

    [soundOnOffMatrix selectCell:[soundOnOffMatrix cellWithTag:1]];
    [panelOnOffMatrix selectCell:[panelOnOffMatrix cellWithTag:1]];

    [hoursField setDelegate:self];
    [minutesField setDelegate:self];
    [secondsField setDelegate:self];
    
    [mainWindow makeKeyAndOrderFront:self];

    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:timerSelector userInfo:nil repeats:YES];
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
    return YES;
}

- (BOOL)applicationShouldTerminate:(NSApplication *)sender
{
    if([reminderArray count])
      {
        NSBeep();
        switch (NSRunAlertPanel(@"EggTimer Warning", @"There are still reminders in the list.\nAre you sure you want to quit?", @"Quit", @"No", nil))
          {
            case 0:
                [self showWindow:self];
                return NO;
                break;
            case 1:
                return YES;
                break;
          }

      }
    return YES;
}

- (void)cancelReminderIdenticalTo:(id)aReminder
{
    [aReminder cancelReminder];
    [remindersTable reloadData];
    [self updateControls];
}

- (void)cancelSelectedReminder:(id)sender
{
    int rowIndex = [remindersTable selectedRow];
    if(rowIndex > -1)
      {
        [self cancelReminderIdenticalTo:[reminderArray objectAtIndex:rowIndex]];
      }
    else
      {
        NSBeep();
        NSRunAlertPanel(@"EggTimer Warning",@"Nothing to cancel!", @"OK", nil, nil);
      }
}

- (void)deleteReminderIdenticalTo:(id)aReminder
{
    int rowIndex = [remindersTable selectedRow];
    [aReminder cancelReminder];
    [reminderArray removeObjectIdenticalTo:aReminder];
    if(rowIndex == 0)
      {
        rowIndex = 1;
      }
    [remindersTable selectRow:(rowIndex-1) byExtendingSelection:NO];
    [remindersTable reloadData];
    [self updateControls];
}

- (void)deleteSelectedReminder:(id)sender
{
    int rowIndex = [remindersTable selectedRow];
    if(rowIndex > -1)
      {
        [self deleteReminderIdenticalTo:[reminderArray objectAtIndex:rowIndex]];
      }
    else
      {
        NSBeep();
        NSRunAlertPanel(@"EggTimer Warning",@"Nothing to delete!", @"OK", nil, nil);
      }
}

- (int)numberOfRowsInTableView:(NSTableView *)theTableView
{
    return [reminderArray count];
}

- (void)reloadData
{
    [dayField setStringValue:[[[NSDate date]
        descriptionWithCalendarFormat:@"%a" timeZone:nil
        locale:nil] uppercaseString]];
    [dateField setStringValue:[[NSDate date]
        descriptionWithCalendarFormat:@"%d" timeZone:nil
        locale:nil]];
    [monthField setStringValue:[[[NSDate date]
        descriptionWithCalendarFormat:@"%b" timeZone:nil
        locale:nil] uppercaseString]];
    [timeField setStringValue:[[NSDate date]
            descriptionWithCalendarFormat:@"%H:%M:%S" timeZone:nil
            locale:nil]];
    [remindersTable reloadData];
}

- (void)reminderDue:(NSTimer *)sender
{
    Reminder *aReminder;
    aReminder = [sender userInfo];
    if([aReminder shouldEmitSound])
      {
        NSBeep();
      }
    if([aReminder shouldShowAlertPanel])
      {
        switch (NSRunAlertPanel(@"EggTimer Reminder", [aReminder stringValue], @"OK", @"Expire", @"Delete"))
          {
            case 1:
                break;
            case 0:
                [self cancelReminderIdenticalTo:aReminder];
                break;
            case -1:
                [self deleteReminderIdenticalTo:aReminder];
                break;
          }
      }
}

- (void)replaceReminder:(id)sender
{
    Reminder *aReminder;
    int selectedRow = [remindersTable selectedRow];
    if (selectedRow > -1 && selectedRow < [reminderArray count])
      {
        aReminder = [reminderArray objectAtIndex:selectedRow];
        if(aReminder)
          {
            [self addReminder:self atIndex:selectedRow];
            [self deleteReminderIdenticalTo:aReminder];
            [remindersTable selectRow:selectedRow byExtendingSelection:NO];
            [self updateControls];
          }
      }
    else
      {
        NSBeep();
        NSRunAlertPanel(@"EggTimer Warning",@"Nothing to replace!", @"OK", nil, nil);
      }
}

- (void)setAbsoluteOrRelative:(id)sender
{
    if([[sender selectedCell] tag] == 0)
      {
        if ([[repeatOnOffMatrix selectedCell] tag] == 1)
          {
            NSBeep();
            [repeatOnOffMatrix selectCell:[repeatOnOffMatrix cellWithTag:0]];
          }
        [[repeatOnOffMatrix cellWithTag:1] setEnabled:NO];
      }
    else
      {
        [[repeatOnOffMatrix cellWithTag:1] setEnabled:YES];
      }
}

- (void)setOnceOrRepeats:(id)sender
{
    if([[sender selectedCell] tag] == 0)
      {
        [[absoluteRelativeMatrix cellWithTag:0] setEnabled:YES];
      }
    else
      {
        if([[absoluteRelativeMatrix selectedCell] tag] == 0)
          {
            NSBeep();
            [absoluteRelativeMatrix selectCell:[absoluteRelativeMatrix cellWithTag:1]];
          }
        [[absoluteRelativeMatrix cellWithTag:0] setEnabled:NO];
      }
}

- (void)showWindow:(id)sender
{
    [mainWindow makeKeyAndOrderFront:self];
}

- (id)tableView:(NSTableView *)theTableView objectValueForTableColumn: (NSTableColumn *)theColumn row:(int)rowIndex;
{
    int hours, minutes, seconds;

    if ([[theColumn identifier] isEqualToString:@"reminder"])
      {
        return [[reminderArray objectAtIndex:rowIndex] stringValue];
      }
        else if ([[theColumn identifier] isEqualToString:@"expired"])
          {
            if ([[reminderArray objectAtIndex:rowIndex] getValid])
              {
                return [NSImage imageNamed:@"Valid"];
              }
            else
              {
                return [NSImage imageNamed:@"Expired"];
              }
          }
    else if ([[theColumn identifier] isEqualToString:@"time"])
      {
        [[reminderArray objectAtIndex:rowIndex] remainingTime:&hours minutes:&minutes seconds:&seconds];
        return [NSString stringWithFormat:@"%02d:%02d:%02d",hours,minutes,seconds];
      }
    else if ([[theColumn identifier] isEqualToString:@"absolute_relative"])
      {
        if ([[reminderArray objectAtIndex:rowIndex] getRelative])
          {
            return [NSImage imageNamed:@"RelativeTime"];
          }
        else
          {
            return [NSImage imageNamed:@"AbsoluteTime"];
          }
      }
    else if ([[theColumn identifier] isEqualToString:@"once_repeats"])
      {
        if([[reminderArray objectAtIndex:rowIndex] getRepeats])
          {
            return [NSImage imageNamed:@"RepeatOn"];
          }
        else
          {
            return [NSImage imageNamed:@"RepeatOff"];
          }
      }
    else if ([[theColumn identifier] isEqualToString:@"sound"])
      {
        if([[reminderArray objectAtIndex:rowIndex] shouldEmitSound])
          {
            return [NSImage imageNamed:@"SoundOn"];
          }
        else
          {
            return [NSImage imageNamed:@"SoundOff"];
          }
      }
    else if ([[theColumn identifier] isEqualToString:@"alert_panel"])
      {
        if([[reminderArray objectAtIndex:rowIndex] shouldShowAlertPanel])
          {
            return [NSImage imageNamed:@"PanelOn"];
          }
        else
          {
            return [NSImage imageNamed:@"PanelOff"];
          }
      }
    else
      {
        return nil;
      }
}

- (void)textDidEndEditing:(NSNotification *)aNotification
{
    [self takeIntValueFrom:[[aNotification userInfo] objectForKey:@"NSFieldEditor"]];
    NSBeep();
}

- (void)takeIntValueFrom:(id)sender
{
    int hr, min, sec;
    if([sender isEqual:hoursSlider])
      {
        [hoursField setStringValue:[NSString stringWithFormat:@"%02d",[hoursSlider intValue]]];
      }
    else if([sender isEqual:minutesSlider])
      {
        [minutesField setStringValue:[NSString stringWithFormat:@"%02d",[minutesSlider intValue]]];
      }
    else if([sender isEqual:secondsSlider])
      {
        [secondsField setStringValue:[NSString stringWithFormat:@"%02d",[secondsSlider intValue]]];
      }
    else if([sender isEqual:hoursField])
      {
        hr = [hoursField intValue];
        if(hr < 24 && hr >-1)
          {
            [hoursSlider setIntValue:hr];
            [hoursField setStringValue:[NSString stringWithFormat:@"%02d",hr]];
          }
        else
          {
            [hoursField setStringValue:[NSString stringWithFormat:@"%02d",[hoursSlider intValue]]];
          }
        [hoursField selectText:self];
      }
    else if([sender isEqual:minutesField])
      {
        min = [minutesField intValue];
        if(min < 60 && min >-1)
          {
            [minutesSlider setIntValue:min];
            [minutesField setStringValue:[NSString stringWithFormat:@"%02d",min]];
          }
        else
          {
            [minutesField setStringValue:[NSString stringWithFormat:@"%02d",[minutesSlider intValue]]];
          }
        [minutesField selectText:self];
      }
    else if([sender isEqual:secondsField])
      {
        sec = [secondsField intValue];
        if(sec < 61 && sec >-1)
          {
            [secondsSlider setIntValue:sec];
            [secondsField setStringValue:[NSString stringWithFormat:@"%02d",sec]];
          }
        else
          {
            [secondsField setStringValue:[NSString stringWithFormat:@"%02d",[secondsSlider intValue]]];
          }
        [secondsField selectText:self];
      }
}

- (void)updateControls
{
    int rowIndex;
    int hours, minutes, seconds;
    rowIndex = [remindersTable selectedRow];
    if([reminderArray count] < 1)
      {
        [cancelButton setEnabled:NO];
        [deleteButton setEnabled:NO];
        [replaceButton setEnabled:NO];
        [cancelMenuItem setEnabled:NO];
        [deleteMenuItem setEnabled:NO];
        [replaceMenuItem setEnabled:NO];
      }
    else if(rowIndex > -1 && rowIndex < [reminderArray count])
      {
        [cancelButton setEnabled:YES];
        [deleteButton setEnabled:YES];
        [replaceButton setEnabled:YES];
        [cancelMenuItem setEnabled:YES];
        [deleteMenuItem setEnabled:YES];
        [replaceMenuItem setEnabled:YES];
        [reminderMessageField setStringValue:[[reminderArray objectAtIndex:rowIndex] stringValue]];
        if([[reminderArray objectAtIndex:rowIndex] getRepeats])
          {
            [repeatOnOffMatrix selectCell:[repeatOnOffMatrix cellWithTag:1]];
          }
        else
          {
            [repeatOnOffMatrix selectCell:[repeatOnOffMatrix cellWithTag:0]];
            [[absoluteRelativeMatrix cellWithTag:0] setEnabled:YES];
          }

        if([[reminderArray objectAtIndex:rowIndex] getRelative])
          {
            [absoluteRelativeMatrix selectCell:[absoluteRelativeMatrix cellWithTag:1]];
            [[repeatOnOffMatrix cellWithTag:1] setEnabled:YES];
          }
        else
          {
            [[absoluteRelativeMatrix cellWithTag:0] setEnabled:YES];
            [[repeatOnOffMatrix cellWithTag:1] setEnabled:NO];
            [absoluteRelativeMatrix selectCell:[absoluteRelativeMatrix cellWithTag:0]];
          }

        if([[reminderArray objectAtIndex:rowIndex] shouldEmitSound])
          {
            [soundOnOffMatrix selectCell:[soundOnOffMatrix cellWithTag:1]];
          }
        else
          {
            [soundOnOffMatrix selectCell:[soundOnOffMatrix cellWithTag:0]];
          }

        if([[reminderArray objectAtIndex:rowIndex] shouldShowAlertPanel])
          {
            [panelOnOffMatrix selectCell:[panelOnOffMatrix cellWithTag:1]];
          }
        else
          {
            [panelOnOffMatrix selectCell:[panelOnOffMatrix cellWithTag:0]];
          }

        if([[reminderArray objectAtIndex:rowIndex] getValid])
          {
            [[reminderArray objectAtIndex:rowIndex] remainingTime:&hours minutes:&minutes seconds:&seconds];
            [hoursField setStringValue:[NSString stringWithFormat:@"%02d",hours]];
            [minutesField setStringValue:[NSString stringWithFormat:@"%02d",minutes]];
            [secondsField setStringValue:[NSString stringWithFormat:@"%02d",seconds]];
            [hoursSlider setIntValue:hours];
            [minutesSlider setIntValue:minutes];
            [secondsSlider setIntValue:seconds];
         }
        else
         {
            [hoursField setStringValue:@"00"];
            [minutesField setStringValue:@"00"];
            [secondsField setStringValue:@"00"];
            [hoursSlider setIntValue:0];
            [minutesSlider setIntValue:0];
            [secondsSlider setIntValue:0];
         }
      }
}

@end
