/*
SRAppearancePref.m

Author: Makoto Kinoshita

Copyright 2004-2006 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of 
  conditions and the following disclaimer in the documentation and/or other materials provided 
  with the distribution.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SHIIRA PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

#import "SRAppearancePref.h"
#import "SRPrefDefaultKeys.h"

#import "SREncodings.h"

@implementation SRAppearancePref

//--------------------------------------------------------------//
#pragma mark -- Initialize --
//--------------------------------------------------------------//

- (id)initWithBundle:(NSBundle*)bundle
{
    self = [super initWithBundle:bundle];
    if (!self) {
        return nil;
    }
    
    // Get WebPreferences
    WebPreferences* webPreferences;
    webPreferences = [SRPreference webPreferences];
    
    // Get content
    id  content;
    content = [_objectController content];
    
    // Set font name
    NSFont*     font;
    NSString*   fontName;
    font = [self fontWithFamilyKey:@"standardFontFamily"];
    fontName = [NSString stringWithFormat:@"%@ %d", [font familyName], (int)[font pointSize]];
    if (font) {
        [content setValue:fontName forKey:@"standardFontName"];
        [content setValue:font forKey:@"standardFont"];
    }
    
    font = [self fontWithFamilyKey:@"fixedFontFamily"];
    fontName = [NSString stringWithFormat:@"%@ %d", [font familyName], (int)[font pointSize]];
    if (font) {
        [content setValue:fontName forKey:@"fixedFontName"];
        [content setValue:font forKey:@"fixedFont"];
    }
    
    font = [self fontWithFamilyKey:@"serifFontFamily"];
    fontName = [NSString stringWithFormat:@"%@", [font familyName]];
    if (font) {
        [content setValue:fontName forKey:@"serifFontName"];
        [content setValue:font forKey:@"serifFont"];
    }
    
    font = [self fontWithFamilyKey:@"sansSerifFontFamily"];
    fontName = [NSString stringWithFormat:@"%@", [font familyName]];
    if (font) {
        [content setValue:fontName forKey:@"sansSerifFontName"];
        [content setValue:font forKey:@"sansSerifFont"];
    }
    
    font = [self fontWithFamilyKey:@"cursiveFontFamily"];
    fontName = [NSString stringWithFormat:@"%@", [font familyName]];
    if (font) {
        [content setValue:fontName forKey:@"cursiveFontName"];
        [content setValue:font forKey:@"cursiveFont"];
    }
    
    font = [self fontWithFamilyKey:@"fantasyFontFamily"];
    fontName = [NSString stringWithFormat:@"%@", [font familyName]];
    if (font) {
        [content setValue:fontName forKey:@"fantasyFontName"];
        [content setValue:font forKey:@"fantasyFont"];
    }
    
    return self;
}

- (void)awakeFromNib
{
    NSUserDefaults* defaults;
    defaults = [NSUserDefaults standardUserDefaults];
    
    // Configure encoding pop up
    NSMenu*         encodingMenu;
    NSEnumerator*   enumerator;
    NSMenuItem*     menuItem;
    encodingMenu = [SREncodings textEncodingMenu];
    enumerator = [[encodingMenu itemArray] objectEnumerator];
    while (menuItem = [enumerator nextObject]) {
        [menuItem setTarget:self];
    }
    [_encodingsPopUp setMenu:encodingMenu];
    
    // Update default encoding popup
    NSStringEncoding    encoding;
    int                 encodingIndex;
    encoding = [[defaults objectForKey:SRDefaultTextEncoding] unsignedIntValue];
    encodingIndex = [_encodingsPopUp indexOfItemWithTag:encoding];
    if (encodingIndex != -1 && encodingIndex < [_encodingsPopUp numberOfItems]) {
        [_encodingsPopUp selectItemAtIndex:encodingIndex];
    }
}

//--------------------------------------------------------------//
#pragma mark -- Web preferences font handling --
//--------------------------------------------------------------//

- (NSFont*)fontWithFamilyKey:(NSString*)familyKey
{
    // Check argument
    if (!familyKey) {
        return nil;
    }
    
    // Get WebPreferences
    WebPreferences* webPreferences;
    webPreferences = [SRPreference webPreferences];
    
    // Get family name
	NSString*   familyName;
    familyName = [webPreferences valueForKey:familyKey];
    if (!familyName) {
        return nil;
    }
    
    // Get font size
    int fontSize;
    fontSize = [NSFont systemFontSize];
    if ([familyKey isEqualToString:@"standardFontFamily"]) {
        fontSize = [webPreferences defaultFontSize];
    }
    else if ([familyKey isEqualToString:@"fixedFontFamily"]) {
        fontSize = [webPreferences defaultFixedFontSize];
    }
    else {
        fontSize = [NSFont systemFontSize];
    }
    
    // Create font
    return [NSFont fontWithName:familyName size:fontSize];
}

- (void)setFont:(NSFont*)font withFamilyKey:(NSString*)familyKey
{
    // Check argument
    if (!font || !familyKey) {
        return;
    }
    
    // Get WebPreferences
    WebPreferences* webPreferences;
    webPreferences = [SRPreference webPreferences];
    
    // Set family name
    NSString*   familyName;
    familyName = [font familyName];
    if (familyName) {
        [webPreferences setValue:familyName forKey:familyKey];
    }
    
    // Set font size
    int fontSize;
    fontSize = [font pointSize];
    if ([familyKey isEqualToString:@"standardFontFamily"]) {
        [webPreferences setDefaultFontSize:fontSize];
    }
    if ([familyKey isEqualToString:@"fixedFontFamily"]) {
        [webPreferences setDefaultFixedFontSize:fontSize];
    }
}

//--------------------------------------------------------------//
#pragma mark -- Actions --
//--------------------------------------------------------------//

- (NSString*)_fontFamilyKeyWithButtonTag:(int)tag
{
	switch (_fontButtonTag) {
	case SRAppearanceStandardFont:  return @"standardFontFamily";
	case SRAppearanceFixedFont:     return @"fixedFontFamily";
	case SRAppearanceSerifFont:     return @"serifFontFamily";
	case SRAppearanceSansSerifFont: return @"sansSerifFontFamily";
	case SRAppearanceCursiveFont:   return @"cursiveFontFamily";
	case SRAppearanceFantasyFont:   return @"fantasyFontFamily";
    }
    
    return nil;
}

- (void)showFontPanelAction:(id)sender
{
    // Get tag of font button
	_fontButtonTag = [sender tag];
	
    // Get preferences key
	NSString*   key;
    key = [self _fontFamilyKeyWithButtonTag:_fontButtonTag];
    if (!key) {
		return;
	}
	
    // Get font
    NSFont* font;
    font = [self fontWithFamilyKey:key];
    if (!font) {
        return;
    }
    
    // Set font font manager
    NSFontManager*  fontMgr;
    fontMgr = [NSFontManager sharedFontManager];
	[fontMgr setSelectedFont:font isMultiple:NO];
    
    // Show font panel
	NSFontPanel*	fontPanel;
	fontPanel = [fontMgr fontPanel:YES];
	if (![fontPanel isVisible]) {
		[fontPanel orderFront:self];
	}
}

- (void)changeFont:(id)sender
{
    // Get preferences key
	NSString*   key;
    key = [self _fontFamilyKeyWithButtonTag:_fontButtonTag];
    if (!key) {
		return;
	}
	
    // Get content
    id  content;
    content = [_objectController content];
    
    // Convert font
	NSFont* font;
	NSFont* convertedFont;
	font = [self fontWithFamilyKey:key];
	convertedFont = [sender convertFont:font];
	
    // Set font
    [self setFont:convertedFont withFamilyKey:key];
    
    // Update content value
    if ([key isEqualToString:@"standardFontFamily"]) {
        NSString*   fontName;
        fontName = [NSString stringWithFormat:@"%@ %d", 
                [convertedFont familyName], (int)[convertedFont pointSize]];
        [content setValue:fontName forKey:@"standardFontName"];
        [content setValue:convertedFont forKey:@"standardFont"];
    }
    if ([key isEqualToString:@"fixedFontFamily"]) {
        NSString*   fontName;
        fontName = [NSString stringWithFormat:@"%@ %d", 
                [convertedFont familyName], (int)[convertedFont pointSize]];
        [content setValue:fontName forKey:@"fixedFontName"];
        [content setValue:convertedFont forKey:@"fixedFont"];
    }
    if ([key isEqualToString:@"serifFontFamily"]) {
        [content setValue:[convertedFont familyName] forKey:@"serifFontName"];
        [content setValue:convertedFont forKey:@"serifFont"];
    }
    if ([key isEqualToString:@"sansSerifFontFamily"]) {
        [content setValue:[convertedFont familyName] forKey:@"sansSerifFontName"];
        [content setValue:convertedFont forKey:@"sansSerifFont"];
    }
    if ([key isEqualToString:@"cursiveFontFamily"]) {
        [content setValue:[convertedFont familyName] forKey:@"cursiveFontName"];
        [content setValue:convertedFont forKey:@"cursiveFont"];
    }
    if ([key isEqualToString:@"fantasyFontFamily"]) {
        [content setValue:[convertedFont familyName] forKey:@"fantasyFontName"];
        [content setValue:convertedFont forKey:@"fantasyFont"];
    }
}

- (void)setTextEncodingAction:(id)sender
{
    NSUserDefaults* defaults;
    defaults = [NSUserDefaults standardUserDefaults];
    
    // Get encoding value from tag
    NSStringEncoding    encoding;
    encoding = [sender tag];
    
    // Get value transformer for encoding name
    NSValueTransformer* transformer;
    transformer = [NSValueTransformer valueTransformerForName:SRIANAToEncodingTransformerName];
    
    NSString*   encodingName;
    
    // For Japanese aut detection
    if (encoding == SRJapaneseAutoDetectEncoding) {
        // Set Sfhit JIS as default encoding, it enables Japanese auto detection
        encodingName = [transformer reverseTransformedValue:
                [NSNumber numberWithUnsignedInt:SRConvertedShiftJISStringEncoding]];
    }
    else {
        // Set web preferences default encoding
        encodingName = [transformer reverseTransformedValue:
                [NSNumber numberWithUnsignedInt:encoding]];
    }
    
    [[self webPreferences] setDefaultTextEncodingName:encodingName];
    
    // Set it default database
    [defaults setObject:[NSNumber numberWithUnsignedInt:encoding] 
            forKey:SRDefaultTextEncoding];
}

@end
