/*$Copyright:
 * Copyright (C) 1992.5.22. Recruit Co.,Ltd. 
 * Institute for Supercomputing Research
 * All rights reserved.
 * NewsBase  by ISR, Kazuto MIYAI, Gary ARAKAKI, Katsunori SUZUKI, Kok-meng Lue
 *
 * You may freely copy, distribute and reuse the code in this program under 
 * following conditions.
 * - to include this notice in the source code, if it is to be distributed 
 *   with source code.
 * - to add the file named "COPYING" within the code, which shall include 
 *   GNU GENERAL PUBLIC LICENSE(*).
 * - to display an acknowledgement in binary code as follows: "This product
 *   includes software developed by Recruit Co.,Ltd., ISR."
 * - to display a notice which shall state that the users may freely copy,
 *   distribute and reuse the code in this program under GNU GENERAL PUBLIC
 *   LICENSE(*)
 * - to indicate the way to access the copy of GNU GENERAL PUBLIC LICENSE(*)
 *
 *   (*)GNU GENERAL PUBLIC LICENSE is stored in the file named COPYING
 * 
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
$*/
/* IPreferenceControl.m */

#import "IPreferenceControl.h"
#import <appkit/FormCell.h>
#import <appkit/Matrix.h>
#import <appkit/Panel.h>
#import <appkit/Application.h>
#import <appkit/PrintInfo.h>
#import <defaults.h>
#import <string.h>
#import <libc.h>
#import <objc/hashtable.h>
#import "errdebug.h"
#import "data_types.h"
#import "Localization.h"

#define LoStr(key)      doLocalString(NULL,key,NULL)

@implementation IPreferenceControl

static NXDefaultsVector MMEditorDefaultsVector = {
	{DISTRIBUTION, "fj"},
	{SAVEDIRECTORY, ""},
	{FROM, ""},
	{REPLYTO, ""},
//        {KANJICODE, "JIS"},
	{MULTIPLEVIEWERFLAG, "No"},
	{FONT, "FixedRyuminCourier-Bold:14"},
	{EDITOR_SIZE, "640:640"},
	{EDITOR_LOCATION, "100:600"},
        {PRINT_INFO_SCALING_FACTOR, "0.70"},
        {JFIF_OR_TIFF, "JFIF"},
        {JPEGCOMPRESSIONFACTOR, "75"},
	{NULL}
};

- init
{
    char	*save_dir;
    const char	*home_dir, *newsbase_dir="NewsBase";
//    char	*newsrc_dir;
//    const char	*newsrc_file=".newsrc";
    char	*get_mail_address();
    const char	*printInfoScalingFactor;    

    [super init];

    if(!(NXRegisterDefaults(OWNER, MMEditorDefaultsVector))) {
	NXRunAlertPanel(LoStr("NewsBase"),LoStr("can't open default database")
	,LoStr("OK"),NULL,NULL);
    }
    /* if value for FROM =="", "user@machine.domain" is set */
    if (!(strcmp(NXGetDefaultValue(OWNER, FROM),""))) {
	NXSetDefault (OWNER, FROM, [self getMailAddress]);
    }
    /* if no REPLYTO, "user@machine.domain" */
    if (!(strcmp(NXGetDefaultValue(OWNER, REPLYTO),""))) {
	NXSetDefault (OWNER, REPLYTO, [self getMailAddress]);
    }
    
    /* if value for SAVEDIRECTORY =="", $HOME/NewsBase is set */
    if (!(strcmp(NXGetDefaultValue(OWNER, SAVEDIRECTORY),""))) {
	home_dir = NXHomeDirectory();
	save_dir = (char *)NXZoneMalloc([self zone], 
		    		strlen(home_dir)+strlen(newsbase_dir)+2);
	strcpy (save_dir, home_dir); 
	strcat (save_dir, "/"); 
	strcat (save_dir, newsbase_dir);
	NXSetDefault (OWNER, SAVEDIRECTORY, save_dir);
    }

    if ((printInfoScalingFactor = NXGetDefaultValue(OWNER,
         PRINT_INFO_SCALING_FACTOR)) != 0) {
        [[NXApp printInfo] setScalingFactor:atof(printInfoScalingFactor)];
    }
    return self;
}

- windowDidBecomeKey:sender
{
    [self read:self];
    return self;
}

- write:sender
{
    const char	*save_dir;
    const char *value;
    
    /* check save and newsrc file directory */
    save_dir = [oSaveDirectory stringValue];
    if (*save_dir!='/') {
	NXRunAlertPanel(LoStr("NewsBase"),
	LoStr("please set absolute path name to directory"),
	LoStr("OK"),NULL,NULL);
	return NULL;
    }
    
    /* write value to database in local disk */
    NXSetDefault(OWNER, DISTRIBUTION, value = [oDistribution stringValue]);
    [self updateDefaultsVectorForName:DISTRIBUTION andValue:value];
    NXSetDefault(OWNER, SAVEDIRECTORY, value = [oSaveDirectory stringValue]);
    [self updateDefaultsVectorForName:SAVEDIRECTORY andValue:value];
    NXSetDefault(OWNER, FROM, value = [oFrom stringValue]);
    [self updateDefaultsVectorForName:FROM andValue:value];
    NXSetDefault(OWNER, REPLYTO, value = [oReplyTo stringValue]);
    [self updateDefaultsVectorForName:REPLYTO andValue:value];
//    NXSetDefault(OWNER, KANJICODE, value = [[oKanjiCode selectedCell] title]);
//    [self updateDefaultsVectorForName:KANJICODE andValue:value];
    NXSetDefault(OWNER, MULTIPLEVIEWERFLAG, 
    	value = [[oMultipleViewerFlag selectedCell] title]);
    [self updateDefaultsVectorForName:MULTIPLEVIEWERFLAG andValue:value];
    NXSetDefault(OWNER, JFIF_OR_TIFF,
        value = [[oJFIForTIFF selectedCell] title]);
    [self updateDefaultsVectorForName:JFIF_OR_TIFF andValue:value];
    NXSetDefault(OWNER, JPEGCOMPRESSIONFACTOR,
        value = [oJPEGFactor stringValue]);
    [self updateDefaultsVectorForName:JPEGCOMPRESSIONFACTOR andValue:value];
    NXSetDefault(OWNER, FONT, value = [oFontName stringValue]);
    [self updateDefaultsVectorForName:FONT andValue:value];
    NXWriteDefaults(OWNER, MMEditorDefaultsVector);
    return(self);
}

- read:sender
{
    [oDistribution setStringValue:NXGetDefaultValue(OWNER, DISTRIBUTION)];
    [oFrom setStringValue:NXGetDefaultValue(OWNER, FROM)];
    [oReplyTo setStringValue:NXGetDefaultValue(OWNER, REPLYTO)];

    [oSaveDirectory setStringValue:NXGetDefaultValue(OWNER,SAVEDIRECTORY)];
//    [self _selectCellMatrix:oKanjiCode
//        title:NXGetDefaultValue(OWNER, KANJICODE)];
    [self _selectCellMatrix:oMultipleViewerFlag
	title:NXGetDefaultValue(OWNER, MULTIPLEVIEWERFLAG)];
    [self _selectCellMatrix:oJFIForTIFF
	title:NXGetDefaultValue(OWNER, JFIF_OR_TIFF)];
    [self setJPEGQualityScale:oJFIForTIFF];
    [oJPEGFactor setStringValue:
        NXGetDefaultValue(OWNER, JPEGCOMPRESSIONFACTOR)];
    [oJPEGQualitySlider takeIntValueFrom:oJPEGFactor];
    [oFontName setStringValue:NXGetDefaultValue(OWNER, FONT)];
    return(self);
}

- (void)_selectCellMatrix:matrix title:(const char *)ktitle
{
    int		i;
    id		cell;
    
    if (ktitle == NULL) {
        [matrix selectCellAt:0 :0];
        return;
    }
    for (i=0; i<[matrix cellCount]; i++) {
	cell = [matrix cellAt:0 :i];
	if(!(strcmp([cell title], ktitle))) {
	    [matrix selectCell:cell];
	    break;
	}
    }
}

- (char *)getMailAddress
{
    char	*mail_address;
    char	*user_name, machine_name[256], domain_name[257];

    user_name = NXCopyStringBufferFromZone(getenv("USER"),[self zone]);
    gethostname(machine_name,sizeof(machine_name));
    getdomainname(domain_name + 1, sizeof(domain_name) - 1);
    domain_name[sizeof(domain_name) - 1] = '\0';
    if (domain_name[1] != '\0') {
        domain_name[0] = '.';
    } else {
        domain_name[0] = '\0';
    }
    mail_address = (char *)NXZoneMalloc([self zone],
	    strlen(user_name)+strlen(machine_name)+strlen(domain_name)+3);
    (void)sprintf(mail_address,"%s@%s%s",user_name,machine_name,
							    domain_name);
    return mail_address;
}

- openViewControlPanel:sender
{
    return NULL;
}

- updateDefaultsVectorForName:(const char *)name andValue:(const char *)value
{
    struct _NXDefault *vecPtr;

    for (vecPtr = MMEditorDefaultsVector; vecPtr->name != NULL; ++vecPtr) {
        if (strcmp(vecPtr->name, name) == 0) {
            // possible memory leak here but very small so don't worry
            vecPtr->value = value;
            return(self);
        }
    }
    return(self);
}

// the JPEG slider depends on the type of JPEG (JFIF or TIFF) so we must
// dynamically set the slider chareacteristics

- setJPEGQualityScale:sender
{
    switch([[sender selectedCell] tag]) {
    case 1:
        [oJPEGFactor setIntValue:10];
        [oJPEGQualitySlider setMinValue:1.0];
        [oJPEGQualitySlider setMaxValue:255.0];
        [oJPEGSliderLeftLabel setStringValue:"good"];
        [oJPEGSliderRightLabel setStringValue:"bad"];
        break;
    case 0:
        [oJPEGFactor setIntValue:75];
        [oJPEGQualitySlider setMinValue:0];
        [oJPEGQualitySlider setMaxValue:100.0];
        [oJPEGSliderLeftLabel setStringValue:"bad"];
        [oJPEGSliderRightLabel setStringValue:"good"];
        break;
    }
    [oJPEGQualitySlider takeIntValueFrom:oJPEGFactor];
}

@end

