#import "CompletingTextVIew.h"
#import "Drachma.h"
#import "DrachmaController.h"
#import "OACoreData.h"
#import "OADebug.h"
#import "OACategories.h"
#import "OAMacros.h"
#import "ModeledObjectTypes.h"
#import "DrachmaPayeeManagement.h"
#import "Queries.h"

@implementation CompletingTextView
- (void) awakeFromNib
{
    [self setEditable:YES];
    [self setFieldEditor:YES];
    [self setSelectable:YES];
    
    m_drachma = [m_drachmaController drachma];
}

- (void) setCompletionsEnabled:(BOOL)value
{
    m_completionsEnabled = value;
}

- (NSArray *)completionsForPartialWordRange:(NSRange)charRange indexOfSelectedItem:(int *)index
{
    if (!m_completionsEnabled)
        return nil;
    
    // ignore the partial word range, and get the entire string:
    NSString *word = [self string];    
    m_stringLength = [word length]; // remember how long it was
    
    // find the set of all payees
    NSArray *completions = [[m_drachma managedObjectContext] payeeCompletions:word];
    NSArray *completionStrings = [completions mapArrayWith:@selector(name)];
    return [completionStrings sortedArrayUsingSelector:@selector(compareIgnoringCase:)];
}

- (void)insertCompletion:(NSString *)word 
     forPartialWordRange:(NSRange)charRange 
                movement:(int)movement 
                 isFinal:(BOOL)isFinal
{
    NSRange selRange = NSMakeRange(m_stringLength, [word length] - m_stringLength);
    [self setString:word];
    [self setSelectedRange:selRange];
    
    // if the user did NOT cancel, we have to copy the fields over from
    // the most recent expense of the selected completion
    if (isFinal && movement != NSCancelTextMovement) {
        Payee *payee = [[m_drachma managedObjectContext] payeeNamed:word]; // *should* already exist
        NSSet *expenses = [payee mutableSetValueForKey:@"expenses"];
        Expense *latestExp = nil;
        NSDate *latestDate = nil;
        FOREACH(Expense *, expense, expenses) {
            if (!latestDate || [latestDate compare:[expense date]] == NSOrderedAscending) {
                latestDate = [expense date];
                latestExp = expense;
            }
        } ENDFOREACH;        
        [m_drachmaController loadFieldsFrom:latestExp];
    }
}

@end
