//
//  TeXDistPrefPane.m
//  TeXDistPrefPane
//
//  Created by coder on 08/12/06.
//  Copyright (c) 2006 Laurens'Tribune. All rights reserved.
//

#import "TeXDistPrefPane.h"
#import "TeXDistAuthentication.h"
#import <Carbon/Carbon.h>
#import "TeXDistController.h"
#import "TeXDistCommon.h"
#import "TeXDistributionUtils.h"
#import "TeXDistLoad.h"

@interface TeXDistPrefPane()
@property (readwrite,retain) NSArray * distributions;
@end

@implementation TeXDistPrefPane

@synthesize distributions = iVarDistributions;

- (id)initWithBundle:(NSBundle *)bundle
{
    if ((self = [super initWithBundle:bundle])) {
		// register my embedded help book
		// it seems cocoa does not registers automagically
		if (bundle) {
            [TeXDistLoad setup];
            NSString * bundlePath = bundle.bundlePath;
            CFURLRef myBundleURL = (CFURLRef)[NSURL fileURLWithPath:bundlePath];// bridge
            if (myBundleURL) {
                FSRef myBundleRef;
                if (CFURLGetFSRef(myBundleURL, &myBundleRef)) {
                    TeXDistLog(0,@"TeXDistPrefPane - Register help book: %@", myBundleURL);
                    OSStatus err = AHRegisterHelpBook(&myBundleRef);
                    if (err) {
                        TeXDistLog(TeXDistLogLevelAlways,@"TeXDistPrefPane - Could not register help book at %@\ndue to error:%i",myBundleURL,err);
                    } else {
                        TeXDistLog(0,@"TeXDistPrefPane - Help book registered, if any...");
                    }
                } else {
                    TeXDistLog(TeXDistLogLevelAlways,@"TeXDistPrefPane - Could not register help book at %@\nbecause I could not create a CFURLRef",myBundleURL);
                }
            } else {
                TeXDistLog(TeXDistLogLevelAlways,@"TeXDistPrefPane - Could not register help book at %@\nbecause I could not create a FSRef",myBundleURL);
            }
		}
        self.distributions = [NSArray array];
        
    }
    return self;
}
- (void) didSelect;
{
	NSLog(@"**** [TeXDistPrefPane didSelect]: There must be an active distribution... Checking");
	[super didSelect];
    TeXDistController * SC = [TeXDistController sharedController];
    [SC resetAndReturnError:NULL];
    self.distributions = SC.distributions;
	if (NOT self.distributions.count) {
		NSRunAlertPanel(IL8N(@"NO TEX DISTRIBUTION AVAILABLE"), IL8N(@"PLEASE INSTALL A TEX DISTRIBUTION"), nil,nil,nil);
    }
	return;
}
- (void) didUnselect;
{
	[[TeXDistAuthentication sharedInstance] invalidateCredentials];
	return;
}
- (BOOL)isDescriptionEditable;
{
	return NO;
}
- (NSArray *)sortDescriptors;
{
	return [NSArray arrayWithObjects:
				[[[NSSortDescriptor alloc] initWithKey:@"modificationDate" ascending:NO] autorelease],
				[[[NSSortDescriptor alloc] initWithKey:@"displayName.lowercaseString" ascending:NO] autorelease],
					nil];
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=  tableViewSelectionDidChange:
- (void)tableViewSelectionDidChange:(NSNotification *)notification;
/*"Description forthcoming
Version History: jlaurens AT users DOT sourceforge DOT net
- 2.0
To Do List:
"*/
{
	[descriptionTextView scrollRangeToVisible:NSMakeRange(0,0)];
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=  tableView:toolTipForCell:rect:tableColumn:row:mouseLocation::
- (NSString *)tableView:(NSTableView *)tv toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc row:(NSInteger)row mouseLocation:(NSPoint)mouseLocation;
/*"Version History: jlaurens AT users DOT sourceforge DOT net
- 2.0
To Do List:
"*/
{
	NSArray * objects = [distributionsController arrangedObjects];
	id O = [objects objectAtIndex:row];
	if ([tc.identifier isEqual:@"displayName"]) {
		return [O valueForKey:@"fileName"];
	}
	if ([tc.identifier isEqual:@"default"]) {
		NSString * key = ([cell state] == NSOnState)?
			@"Button is checked for the current system wide TeX distribution.":
			@"Check this button to choose a current system wide TeX distribution.";
		return IL8N(key);
	}
	if ([tc.identifier isEqual:@"architecture"]) {
		NSString * key = ([cell state] == NSOnState)?
			@"Button is checked for the current system wide TeX distribution.":
			@"Check this button to choose a current system wide TeX distribution.";
		return IL8N(key);
	}
    return nil;
}
- (NSString *) prettyVersion;
{
	NSBundle * bundle = [NSBundle bundleForClass:[TeXDistPrefPane class]];
	return [NSString stringWithFormat:@"v. %@",[bundle objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey]];
}
- (IBAction) showHelp:(id)sender;
{
    CFPropertyListRef ref = CFPreferencesCopyValue (
        CFSTR("DontUseHelpLauncher"),
        (CFStringRef)TeXDistPreferenceID,
        kCFPreferencesCurrentUser,
        kCFPreferencesAnyHost
    );
    if  (ref AND CFGetTypeID(ref) == CFStringGetTypeID() AND [(NSString*)ref boolValue]) {
        [[NSHelpManager sharedHelpManager] openHelpAnchor:TeXDist_HELP_BOOK_ACCESS inBook:TeXDist_HELP_BOOK_ID];
    } else {
        NSBundle * bundle = [NSBundle bundleForClass:[TeXDistPrefPane class]];
        NSString * helpLauncher = [[bundle.sharedSupportPath stringByAppendingPathComponent:TeXDist_HELP_LAUNCHER_NAME] stringByAppendingPathExtension:@"app"];
        if (NOT [[NSWorkspace sharedWorkspace] launchApplication:helpLauncher]) {
            NSLog(@"TeXDist preference pane: help launcher is not available (%@)",helpLauncher);
        }
    }
    if (ref) {
        CFRelease(ref);
    }
	return;
}
- (NSString *)chooseDistributionLabel;
{
    return IL8N(@"Choose a system wide TeX distribution:");
}
@end
