//
//  ICeCoffEEServicePrefController.m
//  ICeCoffEE APE
//
//  Created by Nicholas Riley on Fri Jun 06 2003.
//  Copyright (c) 2003 Nicholas Riley. All rights reserved.
//

#import "ICeCoffEEShared.h"
#import "ICeCoffEESetServicesMenu.h"
#import "ICeCoffEEServicePrefController.h"
#import "ICeCoffEENonHighlightingButtonCell.h"
#import "ICeCoffEENonHighlightingTextFieldCell.h"
#import <objc/objc.h>
#import <ApplicationEnhancer/ApplicationEnhancer.h>

static NSNumber *ICCF_SERVICE_SHOWN, *ICCF_SERVICE_HIDDEN, *ICCF_SERVICE_MIXED;
static NSDictionary *ICCF_SERVICE_OPTION_HIDDEN;

static float ICCF_TableViewCellHeight(NSTableView *tableView) {
    return ([tableView rowHeight] + [tableView intercellSpacing].height);
}

static inline NSCellStateValue ICCF_ServiceItemState(id <NSMenuItem> item) {
    id state = [item representedObject];
    return (state == nil) ? NSOnState : [state intValue];
}

static void ICCF_PropagateServiceStateChange(NSMenu *menu, id state) {
    NSEnumerator *e = [[menu itemArray] objectEnumerator];
    NSMenuItem *item;
    NSMenu *submenu;

    while ( (item = [e nextObject]) != nil) {
        submenu = [item submenu];
        if (submenu != nil) {
            ICCF_PropagateServiceStateChange(submenu, state);
            [item setRepresentedObject: (state == nil) ? ICCF_SERVICE_SHOWN : state];
        }
        [item setRepresentedObject: state];
    }
}

static NSCellStateValue ICCF_PropagateServiceState(id <NSMenuItem> item, NSMenuItem *changedItem) {
    NSMenu *submenu = [item submenu];
    if (submenu == nil) return ICCF_ServiceItemState(item);

    if (item == changedItem) ICCF_PropagateServiceStateChange(submenu, [item representedObject]);

    BOOL areOn = NO, areOff = NO;
    NSEnumerator *e = [[submenu itemArray] objectEnumerator];
    NSMenuItem *subItem;
    while ( (subItem = [e nextObject]) != nil) {
        switch (ICCF_PropagateServiceState(subItem, changedItem)) {
            case NSOnState: if (!areOff) { areOn = YES; continue; }
                break;
            case NSOffState: if (!areOn) { areOff = YES; continue; }
                break;
            case NSMixedState:
                break;
        }
        [item setRepresentedObject: ICCF_SERVICE_MIXED];
        return NSMixedState;
    }
    if (areOn) {
        [item setRepresentedObject: ICCF_SERVICE_SHOWN];
        return NSOnState;
    } else {
        [item setRepresentedObject: ICCF_SERVICE_HIDDEN];
        return NSOffState;
    }
}

static NSMutableDictionary *ICCF_RetainedServiceOptionsDictionary(NSMenu *menu) {
    NSEnumerator *e = [[menu itemArray] objectEnumerator];
    NSMenuItem *item;
    NSMenu *submenu;
    NSMutableDictionary *dict = nil, *subDict = nil, *submenuDict = nil;

    while ( (item = [e nextObject]) != nil) {
        submenu = [item submenu];
        if (ICCF_ServiceItemState(item) == NSOffState) {
            subDict = [ICCF_SERVICE_OPTION_HIDDEN retain];
        } else if (submenu != nil) {
            submenuDict = ICCF_RetainedServiceOptionsDictionary(submenu);
            if (submenuDict == nil)
                continue;
            subDict = [[NSDictionary alloc] initWithObjectsAndKeys: submenuDict, kICServiceSubmenu, nil];
            [submenuDict release];
        } else continue;
        if (dict == nil) {
            dict = [[NSMutableDictionary alloc] init];
        }
        [dict setObject: subDict forKey: [item title]];
        [subDict release];
    }
    return dict;
}

static void ICCF_RestoreServiceOptionsDictionary(NSMenu *menu, NSDictionary *dict) {
    NSEnumerator *e = [dict keyEnumerator];
    NSString *itemTitle;
    NSDictionary *subDict, *submenuDict;
    id <NSMenuItem> item;
    NSMenu *submenu;

    // XXX handle exceptions
    while ( (itemTitle = [e nextObject]) != nil) {
        item = [menu itemWithTitle: itemTitle];
        if (item == nil) continue;
        subDict = [dict objectForKey: itemTitle];
        if ([[subDict objectForKey: (NSString *)kICServiceHidden] boolValue]) {
            [item setRepresentedObject: ICCF_SERVICE_HIDDEN];
        }
        if ( (submenu = [item submenu]) != nil) {
            submenuDict = [subDict objectForKey: (NSString *)kICServiceSubmenu];
            if ([submenuDict count] == 0)
                ICCF_PropagateServiceStateChange(submenu, ICCF_SERVICE_HIDDEN);
            else
                ICCF_RestoreServiceOptionsDictionary(submenu, submenuDict);
        }
    }
}

@implementation ICeCoffEEServicePrefController

#pragma mark class initialization

+ (void)initialize;
{
    ICCF_SERVICE_SHOWN = [[NSNumber alloc] initWithInt: NSOnState];
    ICCF_SERVICE_HIDDEN = [[NSNumber alloc] initWithInt: NSOffState];
    ICCF_SERVICE_MIXED = [[NSNumber alloc] initWithInt: NSMixedState];
    ICCF_SERVICE_OPTION_HIDDEN = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithBool: YES], kICServiceHidden, nil];
}

#pragma mark initialize-release

- (id)initWithParentWindow:(NSWindow *)parent;
{
    if ( (self = [self initWithWindowNibName: @"Select services"])) {
        NSWindow *window = [self window]; // connect outlets
        NSButtonCell *checkBoxCell = [[ICeCoffEENonHighlightingButtonCell alloc] init];
        [checkBoxCell setButtonType: NSSwitchButton];
        [checkBoxCell setImagePosition: NSImageOnly];
        [checkBoxCell setAllowsMixedState: YES];
        [[serviceOutline tableColumnWithIdentifier: @"show"] setDataCell: checkBoxCell];
        [checkBoxCell release];

        NSTextFieldCell *textFieldCell = [[serviceOutline tableColumnWithIdentifier: @"service"] dataCell];
        ((struct objc_object *)textFieldCell)->isa = [ICeCoffEENonHighlightingTextFieldCell class];

        textFieldCell = [[serviceOutline tableColumnWithIdentifier: @"key"] dataCell];
        ((struct objc_object *)textFieldCell)->isa = [ICeCoffEENonHighlightingTextFieldCell class];

        [window setResizeIncrements: NSMakeSize(1, ICCF_TableViewCellHeight(serviceOutline))];
        if (parent != nil) {
            [NSApp beginSheet: window modalForWindow: parent modalDelegate: self didEndSelector: nil contextInfo: nil];
        } else {
            [window center];
            [window makeKeyAndOrderFront: nil];
        }
    }
    return self;
}

- (void)dealloc;
{
    [servicesMenu release];
    [super dealloc];
}

#pragma mark actions

- (IBAction)showAll:(NSButton *)sender;
{
    ICCF_PropagateServiceStateChange(servicesMenu, nil);
    [serviceOutline reloadData];
}

- (IBAction)hideAll:(NSButton *)sender;
{
    ICCF_PropagateServiceStateChange(servicesMenu, ICCF_SERVICE_HIDDEN);
    [serviceOutline reloadData];
}

- (void)closeWithReturnCode:(int)returnCode;
{
    if ([[self window] isSheet]) {
        [NSApp endSheet: [self window] returnCode: NSRunAbortedResponse];
    }
    [self close];
}

- (IBAction)cancel:(NSButton *)sender;
{
    [self closeWithReturnCode: NSRunAbortedResponse];
}

- (IBAction)saveChanges:(NSButton *)sender;
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *icDefaults = [[defaults persistentDomainForName: (NSString *)kICBundleIdentifier] mutableCopy];
    NSDictionary *serviceOptions = ICCF_RetainedServiceOptionsDictionary(servicesMenu);
    if (serviceOptions != nil) {
        [icDefaults setObject: serviceOptions forKey: (NSString *)kICServiceOptions];
        [serviceOptions release];
    } else {
        [icDefaults removeObjectForKey: (NSString *)kICServiceOptions];
    }
    [defaults setPersistentDomain: icDefaults forName: (NSString *)kICBundleIdentifier];
    [defaults synchronize];
    APEMessageBroadcast(kICBundleIdentifier, kICPreferencesChanged, NULL);
    [icDefaults release];
    [self closeWithReturnCode: NSRunStoppedResponse];
}

@end

@implementation ICeCoffEEServicePrefController (NSOutlineViewDataSource)

- (int)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item;
{
    if (servicesMenu == nil) {
	servicesMenu = [[NSMenu alloc] initWithTitle: @""];
	ICCF_SetServicesMenu(servicesMenu);
        [servicesMenu update]; // XXX necessary on 10.3? or anywhere?
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *icDefaults = [defaults persistentDomainForName: (NSString *)kICBundleIdentifier];
        NSDictionary *serviceOptions = [icDefaults objectForKey: (NSString *)kICServiceOptions];
        ICCF_RestoreServiceOptionsDictionary(servicesMenu, serviceOptions);
    }
    return [(item == nil ? servicesMenu : [item submenu]) numberOfItems];
}

- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item;
{
    return (item == nil ? YES : [item submenu] != nil);
}

- (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item;
{
    return [(item == nil ? servicesMenu : [item submenu]) itemAtIndex: index];
}

NSAttributedString *ICCF_KeyEquivalentAttributedStringWithModifierFlags(NSString *self, unsigned int modifierFlags);

- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item;
{
    if ([[tableColumn identifier] isEqualToString: @"service"]) {
        return [item title];
    } else if ([[tableColumn identifier] isEqualToString: @"show"]) {
        id state = [item representedObject];
        if ([item submenu] != nil && state == nil) {
            return [NSNumber numberWithInt: ICCF_PropagateServiceState(item, nil)];
        }
        return (state == nil) ? ICCF_SERVICE_SHOWN : state;
    } else if ([[tableColumn identifier] isEqualToString: @"key"]) {
        NSString *equivalent = [item keyEquivalent];
        if (equivalent == nil || [equivalent length] != 1) return nil;
        // XXX Inconsistency between Cocoa and Carbon: always command-shift in Carbon, not in Cocoa.  Since we only patch Cocoa for the moment, keep as is.
        return ICCF_KeyEquivalentAttributedStringWithModifierFlags(equivalent, [item keyEquivalentModifierMask] | ([[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember: [equivalent characterAtIndex: 0]] ? NSShiftKeyMask : 0));
    }
    return nil;
}

- (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item;
{
    if ([[tableColumn identifier] isEqualToString: @"show"]) {
        [item setRepresentedObject: [object boolValue] ? nil : ICCF_SERVICE_HIDDEN];
        
        NSMenu *submenu = [item menu];
        if (submenu == servicesMenu) {
            ICCF_PropagateServiceState(item, item);
        } else {
            NSMenu *supermenu;
            while ( (supermenu = [submenu supermenu]) != servicesMenu) {
                submenu = supermenu;
            }
            ICCF_PropagateServiceState([supermenu itemAtIndex: [supermenu indexOfItemWithSubmenu: submenu]], item);
        }
        [outlineView reloadData];
    }
}

@end

@implementation ICeCoffEEServicePrefController (NSWindowDelegate)

- (NSRect)windowWillUseStandardFrame:(NSWindow *)sender defaultFrame:(NSRect)defaultFrame;
{
    NSWindow *window = [serviceOutline window];
    NSRect frame = [window frame];
    NSScrollView *scrollView = [serviceOutline enclosingScrollView];
    float displayedHeight = [[scrollView contentView] bounds].size.height;
    float heightChange = [[scrollView documentView] bounds].size.height - displayedHeight;
    float heightExcess;

    if (heightChange >= 0 && heightChange <= 1) {
        // either the window is already optimal size, or it's too big
        float rowHeight = ICCF_TableViewCellHeight(serviceOutline);
        heightChange = (rowHeight * [serviceOutline numberOfRows]) - displayedHeight;
    }

    frame.size.height += heightChange;

    if ( (heightExcess = [window minSize].height - frame.size.height) > 1 ||
         (heightExcess = [window maxSize].height - frame.size.height) < 1) {
        heightChange += heightExcess;
        frame.size.height += heightExcess;
    }

    frame.origin.y -= heightChange;

    return frame;
}

@end

@implementation ICeCoffEEServicePrefController (NSWindowNotifications)

- (void)windowWillClose:(NSNotification *)notification;
{
    [self autorelease];
}

@end