/*
**  SmartFolderEditor.m
**
**  Copyright (c) 2004
**
**  Author: Yen-Ju Chen <yjchenx@hotmail.com>
**
**  This program is free software; you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation; either version 2 of the License, or
**  (at your option) any later version.
**
**  This program is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**  GNU General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with this program; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "SmartFolderEditor.h"
#include "AttributesSource.h"
#include "Sources.h"
#include "Utilities.h"
#include "Constants.h"
#include "CriterionView.h"
#include "Criterion.h"

static SmartFolderEditor *sharedInstance;

@implementation SmartFolderEditor

/* CriterionView delegate */
- (void) criterionViewProposeResizing: (CriterionView *) view
                               toSize: (NSSize ) proposedSize
{
  //NSLog(@"propose resize to %@", NSStringFromSize(proposedSize));
  /* Calculate optimal height */
  NSRect editorFrame, viewFrame;
  float optimal_height = proposedSize.height;
  editorFrame = [editor frame];
  viewFrame = [criterionView frame];
  optimal_height = [criterionView optimalHeight];
  float diff = viewFrame.size.height-optimal_height;
  [editor setFrame: NSMakeRect(editorFrame.origin.x,
		               editorFrame.origin.y+diff,
			       editorFrame.size.width,
                               editorFrame.size.height-diff)
           display: YES];
}


/* Actions */

- (void) okAction: (id) sender
{
  [editor endEditingFor: nil];
  [original setCriterion: criterion];
  [editor performClose: sender];
}

- (void) cancelAction: (id) sender
{
  [editor performClose: sender];
}

- (void) numberPopUpButtonAction: (id) sender
{
  unsigned int index = [sender indexOfSelectedItem];
  if (index == 1)
    [criterionView setFloatNumberRegExType: RegExCommaFloatNumber];
  else
    [criterionView setFloatNumberRegExType: RegExDotFloatNumber];
}

- (void) datePopUpButtonAction: (id) sender
{
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  NSString *format;
  unsigned int index = [sender indexOfSelectedItem];
  switch(index)
    {
      case 1:
        [criterionView setDateRegExType: RegExDDMMYYYYDate];
        format = CalendarDateDDMMYYYYInputFormat;
	break;
      case 2:
        [criterionView setDateRegExType: RegExYYYYMMDDDate];
        format = CalendarDateYYYYMMDDInputFormat;
	break;
      default:
        [criterionView setDateRegExType: RegExMMDDYYYYDate];
        format = CalendarDateMMDDYYYYInputFormat;
    }
  [defaults setObject: format forKey: CalendarInputFormatDefault];
}

- (void) matchAllButtonAction: (id) sender
{
  if ([sender state] == NSOnState)
    {
      [criterion setMatchAll: YES];
    }
  else
    {
      [criterion setMatchAll: NO];
    }
}

/* window delegate */
- (BOOL) windowShouldClose: (id) sender
{
  [NSApp stopModal];
  return YES;
}


+ (SmartFolderEditor *) sharedEditor
{
  if (sharedInstance == nil)
    {
       sharedInstance = [[SmartFolderEditor alloc] init];
    }
  return sharedInstance;
}

- (void) setTitle: (NSString *) t
{
  ASSIGN(title, t);
  [editor setTitle: [NSString stringWithFormat: sSmartFolderEditor_, title]];
}

- (void) setCriterion: (Criterion *) c
{
  ASSIGN(original, c);
  [criterion setCriterion: c];

  /* Try to get all subject */
  addAvailableSubjectsIntoCriterion(criterion);

  Sources *sources = [Sources sharedSources];
  unsigned int i, count = [sources count];
  SourceType sourceType;
  NSString *t;
  NSMutableArray *selections = [[NSMutableArray alloc] init];
  /* go through all sources */
  for(i = 0; i < count; i++)
    {
      sourceType = [sources typeOfSourceAtIndex: i];
      switch(sourceType)
        {
          case SourceSmartFolderType:
          case SourceFolderType:
            t = [sources titleAtIndex: i];
	    if ([t isEqualToString: title]) continue;
            [selections addObject: t];
            break;
          case SourceLibraryType:
          case SourceSearchType:
          /* Ignore these type */
            break;
        }
    }
  [criterion setAvailableSelections: selections
                   forSubject: sSource];
  RELEASE(selections);

  if ([criterion numberOfCriterionsInView: criterionView] < 1)
    {
      /* Add first criterion */
      [criterion addCriterionWithSubject: sTitle
	                            verb: CriterionContainsVerb
				  object: @""];
    }

  [criterionView setDelegate: self];
  [criterionView setDataSource: criterion];
  [criterionView reloadData];

  [matchAllButton setState: [criterion matchAll]];
}

- (Criterion *) criterion
{
  return criterion;
}

- (void) awakeFromNib
{
  /* Make sure PopUpButton is selected */
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

  NSString *separator = [defaults stringForKey: NSDecimalSeparator];
  if ([separator isEqualToString: @","])
    [numberPopUpButton selectItemAtIndex: 1];
  else
    [numberPopUpButton selectItemAtIndex: 0];

  NSString *format = [defaults stringForKey: CalendarInputFormatDefault];
  if ([format isEqualToString: CalendarDateDDMMYYYYInputFormat])
    [datePopUpButton selectItemAtIndex: 1];
  else if ([format isEqualToString: CalendarDateYYYYMMDDInputFormat])
    [datePopUpButton selectItemAtIndex: 2];
  else
    [datePopUpButton selectItemAtIndex: 0];

  [criterionView setMaxCriterions: 10];
}

- (void) makeEditorKeyAndOrderFront: (id) sender
{
  NSRect editorFrame, viewFrame;
  float optimal_height;
  [criterionView reloadData];
  /* Calculate optimal height */
  editorFrame = [editor frame];
  viewFrame = [criterionView frame];
  optimal_height = [criterionView optimalHeight];
  [editor setFrame: NSMakeRect(editorFrame.origin.x,
		               editorFrame.origin.y,
			       editorFrame.size.width,
           editorFrame.size.height-(viewFrame.size.height-optimal_height))
           display: NO];
  [editor makeKeyAndOrderFront: sender];
  [NSApp runModalForWindow: editor];
}

- (id) init
{
  self = [super init];

  BOOL result = [NSBundle loadNibNamed: @"SmartFolderEditor" owner: self];
  if (result == NO)
    {
      NSLog(@"Unable to load SmartFolderEditor interface");
      return nil;
    }

  criterion = [[Criterion alloc] init]; 

  return self;
}

- (void) dealloc
{
  RELEASE(criterion);
  RELEASE(title);
  [super dealloc];
}

@end
