/* Copyright (c) 2004, Noah Sorscher
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 	¥ 	Redistributions of source code must retain the above copyright
 * 	notice, this list of conditions and the following disclaimer.
 * 	¥ 	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.
 * 	¥ 	Neither the name of the Noah Sorscher nor the names of its
 * 	contributors may be used to endorse or promote products derived from
 * 	this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER 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 "tLanguages.h"

@implementation tLanguages

- (IBAction)select:(id)sender
{
    int state = [sender state];
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    NSMutableArray *selected = [NSMutableArray arrayWithArray:[defs objectForKey:@"selectedLanguages"]];
    NSNumber *theNumber = [NSNumber numberWithInt:[tLanguages stringToNumber:[sender title]]];
    if (state == NSOnState) {
        [sender setState:NSOffState];
        [langTable removeTableColumn:[langTable tableColumnWithIdentifier:[sender title]]];
        [selected removeObject:theNumber];
    } else {
        [sender setState:NSOnState];
        [langTable addColumnWithName:[sender title]];
        [selected addObject:theNumber];
    }
    [defs setObject:selected forKey:@"selectedLanguages"];
    [defs synchronize];
}

- (IBAction)copySwitch:(id)sender
{   [langTable reloadData];     }

- (IBAction)langMenu:(id)sender
{
    if (![sender isKindOfClass:[NSEvent class]]) return;
    NSMenu *menu = [[[NSMenu alloc] init] autorelease];
    NSArray *langs = [tLanguages stringLangs];
    int i, n = [langs count];
    for (i=0;i<n;i++) {
        NSMenuItem *item = [[[NSMenuItem alloc] init] autorelease];
        [item setTitle:[langs objectAtIndex:i]];
        [item setTarget:self];
		//if (i)
			[item setAction:@selector(select:)];
        int x = i;
        if (x > 94) x += 33;
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"selectedLanguages"] containsObject:[NSNumber numberWithInt:x]])
            [item setState:YES];
        [menu addItem:item];
    }
    [NSMenu popUpContextMenu:menu withEvent:sender forView:nil];
}

- (void)savePrefs
{
    //NSLog(@"languages");
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    [defs setObject:[self selectedLanguages] forKey:@"selectedLanguages"];
    [defs setBool:[toCopy state] forKey:@"tLangToCopy"];
    [langTable autosaveNow];
}

+ (NSArray *)stringLangs
{
    return [NSArray arrayWithObjects:@"English", @"French", @"German", @"Italian", @"Dutch", @"Swedish", @"Spanish", @"Danish", @"Portuguese", @"Norwegian", @"Hebrew", @"Japanese", @"Arabic", @"Finnish", @"Greek", @"Icelandic", @"Maltese", @"Turkish", @"Croatian", @"Traditional Chinese", @"Urdu", @"Hindi", @"Thai", @"Korean", @"Lithuanian", @"Polish", @"Hungarian", @"Estonian", @"Latvian", @"Sami", @"Faroese", @"Farsi", @"Russian", @"Simple Chinese", @"Flemish", @"Irish Gaelic", @"Albanian", @"Romanian", @"Czech", @"Slovak", @"Slovenian", @"Yiddish", @"Serbian", @"Macedonian", @"Bulgarian", @"Ukrainian", @"Belorussian", @"Uzbek", @"Kazakh", @"Azerbaijani Cyrillic", @"Azerbaijani Arabic", @"Armenian", @"Georgian", @"Moldovan", @"Kirghiz", @"Tajiki", @"Turkmen", @"Mongolian", @"Mongolian Cyrillic", @"Pashto", @"Kurdish", @"Kashmiri", @"Sindhi", @"Tibetan", @"Nepali", @"Sanskrit", @"Marathi", @"Bengali", @"Assamese", @"Gujarati", @"Punjabi", @"Oriya", @"Mayalayan", @"Kannada", @"Tamil", @"Telugu", @"Sinhalese", @"Burmese", @"Khmer", @"Lao", @"Vietnamese", @"Indonesian", @"Tagalog", @"Malay Roman", @"Malay Arabic", @"Amharic", @"Tigrinya", @"Oromo", @"Somali", @"Swahili", @"Kinyarwanda", @"Ruanda", @"Rundi", @"Nyanja", @"Chewa", @"Malagasi", @"Esperanto", @"Welsh", @"Basque", @"Katalan", @"Latin", @"Queschua", @"Guarani", @"Aymara", @"Tatar", @"Uighur", @"Dzongkha", @"Javanese", @"Sudanese", @"Galician", @"Afrikaans", @"Breton", @"Inuktitut", @"Scottish", @"Manx", @"Irish Gaelic Script", @"Tongan", @"Greek", @"Greenlandic", @"Azerbaijani Roman", nil];
}

+ (NSString *)numberToString:(int)num
{
    if (langUnspecified == num) return @"Unspecified";
    if (num < 0 || (num > 94 && num < 128) || num > 150) return @"";
    if (num > 94)
        num -= 33;
    return [[tLanguages stringLangs] objectAtIndex:num];
}

+ (NSString *)abbrev:(NSString *)string
{
    NSArray *longs = [NSArray arrayWithObjects:@"Afar", @"Albanian", @"Armenian", @"Basque", @"Bengali", @"Bhutani", @"Bihari", @"Bulgarian", @"Burmese", @"Byelorussian", @"Cambodian", @"Chinese", @"Croatian", @"Czech", @"Dutch", @"Esperanto", @"Estonian", @"Faeroese", @"Fiji", @"Frisian", @"Galician", @"Georgian", @"German", @"Greek", @"Greenlandic", @"Guarani", @"Icelandic", @"Indonesian", @"Interlingua", @"Interlingue", @"Inupiak", @"Inuktitut", @"Irish", @"Javanese", @"Kannada", @"Kashmiri", @"Kazakh", @"Kinyarwanda", @"Kirghiz", @"Kirundi", @"Laothian", @"Latvian", @"Lingala", @"Lithuanian", @"Macedonian", @"Malagasy", @"Malay", @"Malayam", @"Maltese", @"Maori", @"Marathi", @"Mongolian", @"Pashto", @"Persian", @"Polish", @"Portuguese", @"Punjabi", @"Rhaeto-Romance", @"Samoan", @"Sangro", @"Scots Gaelic", @"Serbian", @"Serbo-Croatian", @"Sesotho", @"Setswana", @"Shona", @"Sindhi", @"Siswati", @"Slovak", @"Spanish", @"Swedish", @"Tagalog", @"Tajik", @"Tatar", @"Tibetan", @"Turkish", @"Turkmen", @"Uigur", @"Welch", @"Zhuang", nil];
    NSArray *shorts = [NSArray arrayWithObjects:@"aa", @"sq", @"hy", @"eu", @"bn", @"dz", @"bh", @"bg", @"my", @"be", @"km", @"zh", @"hr", @"cs", @"nl", @"eo", @"et", @"fo", @"fj", @"fy", @"gl", @"ka", @"de", @"el", @"kl", @"gn", @"is", @"id", @"ia", @"ie", @"ik", @"iu", @"ga", @"jw", @"kn", @"ks", @"kk", @"rw", @"ky", @"rn", @"lo", @"lv", @"ln", @"lt", @"mk", @"mg", @"ms", @"ml", @"mt", @"mi", @"mr", @"mn", @"ps", @"fa", @"pl", @"pt", @"pa", @"rm", @"sm", @"sg", @"gd", @"sr", @"sh", @"st", @"tn", @"sn", @"sd", @"ss", @"sk", @"es", @"sv", @"tl", @"tg", @"tt", @"bo", @"tr", @"tk", @"ug", @"cy", @"za", nil];
    int index = [longs indexOfObject:string];
    if (index != NSNotFound) // found a long special case
        return [shorts objectAtIndex:index];
    index = [shorts indexOfObject:string];
    if (index != NSNotFound) // found a short special case
        return [longs objectAtIndex:index];
    if ([string length] > 2) // a long non-special case
        return [[string substringToIndex:2] lowercaseString];
    // a short non-special case
    int i, n = [[[self class] stringLangs] count];
    for (i=0;i<n;i++) {
        NSString *candidate = [[[self class] stringLangs] objectAtIndex:i];
        if ([[candidate lowercaseString] hasPrefix:string])
            return candidate;
    }
    return string;
}

+ (int)stringToNumber:(NSString *)string
{
    if (!string || ![string isKindOfClass:[NSString class]])
        return -1;
    if ([string isEqualToString:@"Unspecified"])
        return langUnspecified;
    int i, n = [[tLanguages stringLangs] count];
    for (i=0;i<n;i++) {
        if ([[[tLanguages stringLangs] objectAtIndex:i] isEqualToString:string]) {
            if (i > 94)
                i += 33;
            return i;
        }
    }
    return -1;
}

id tLangNibInstance = nil;
NSArray *sysLangList = nil;
BOOL awake = NO;

+ (void)collectSysLangs
{
	NSArray *sysLangs = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString *sysLang = nil;
	NSMutableArray *fixedLangs = [NSMutableArray array];
    int i;
    for (i=0;i<[sysLangs count];i++) {
        sysLang = [sysLangs objectAtIndex:i];
        if ([sysLang length] <= 2) sysLang = [[self class] abbrev:sysLang];
		[fixedLangs addObject:sysLang];
    }
	sysLangList = [[NSArray alloc] initWithArray:fixedLangs];
}

- (void)awakeFromNib
{
	if (awake) return;
	awake = YES;
    tLangNibInstance = self;
	NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
	NSMutableArray *sel = [NSMutableArray arrayWithArray:[defs objectForKey:@"selectedLanguages"]];
	if ([sel count] == 0) {
		[sel addObject:[NSNumber numberWithInt:0]];
		[defs setObject:sel forKey:@"selectedLanguages"];
		[defs synchronize];
		[langTable performSelector:@selector(addColumnWithName:) withObject:@"English" afterDelay:0];
	}
	int i, n = [sel count];
	for (i=0;i<n;i++) {
		int num = [[sel objectAtIndex:i] intValue];
		NSString *name = [tLanguages numberToString:num];
		[langTable performSelector:@selector(addColumnWithName:) withObject:name afterDelay:0];
	}
}

+ (NSArray *)systemLanguages
{
	if (!sysLangList) [[self class] collectSysLangs];
	return sysLangList;
}

+ (BOOL)toCopy
{
    return [tLangNibInstance toCopy];
}

- (BOOL)toCopy
{
    return [toCopy state];
}

- (void)restorePrefs
{
    //int n = [[tLanguages stringLangs] count];
    //for (i=0;i<n;i++)
    //    [[menu addItemWithTitle:[[tLanguages stringLangs] objectAtIndex:i] action:@selector(select:) keyEquivalent:@""] setTarget:self];
    
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    /*
    NSArray *langs = [defs objectForKey:@"selectedLanguages"];
    if (langs == nil)
        [[menu itemAtIndex:0] setState:NSOnState];
    else {
        / *
        NSArray *cols = [langTable tableColumns];
        while ([cols count])
            [langTable removeTableColumn:[cols objectAtIndex:0]];
        [langTable addColumnWithName:@"Category"];
        * /
        n = [langs count];
        for (i=0;i<n;i++) {
            x = [[langs objectAtIndex:i] intValue];
            //[langTable addColumnWithName:[tLanguages numberToString:x]];
            if (x > 94)
                x -= 33;
            [[menu itemAtIndex:x] setState:NSOnState];
        }
    }
    */
    [toCopy setState:[defs boolForKey:@"tLangToCopy"]];
    [langTable restoreFromAutosave];
    [langTable reloadData];
}

+ (NSArray *)selectedLanguages
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedLanguages"];
}

- (NSArray *)selectedLanguages
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedLanguages"];
    /*
    NSMutableArray *langs = [[NSMutableArray alloc] init];
    int i;
    for (i=0;i<=94;i++) {
        if ([[menu itemAtIndex:i] state])
            [langs addObject:[NSNumber numberWithInt:i]];
    }
    for (i=128;i<=150;i++) {
        if ([[menu itemAtIndex:i-33] state])
            [langs addObject:[NSNumber numberWithInt:i]];
    }
    return langs;
    */
}

@end

