//
//  TextExport.m
//  drachma
//
//  Created by Nicholas Matsakis on 3/3/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "TextExport.h"
#import "ModeledObjectTypes.h"
#import "ModeledObjectCategories.h"
#import "OACoreData.h"
#import "OACategories.h"
#import "OAMacros.h"

@implementation TextExport

- (Drachma*) drachma
{
    return [m_drachmaController drachma];
}

- (IBAction) textExport:(id)sender
{
    NSManagedObjectContext *mctx = [[self drachma] managedObjectContext];
    if (mctx == nil)
        return;
    
    // Pop up a dialog to get the file name
    NSSavePanel *savePanel = [NSSavePanel savePanel];
    [savePanel setPrompt:@"Choose a file for export"];
    [savePanel setTitle:@"Text Export"];
    int result = [savePanel runModal];
    if (result == NSFileHandlingPanelCancelButton)
        return;
    
    // For now, we only export the line items
    NSString *format = @"%@\t%@\t%@\t%@\t%@";
    NSArray *allExpenses = [mctx allObjectsOfEntityType:@"Expense"];
    NSMutableArray *serializedExpenses = [NSMutableArray arrayWithCapacity:[allExpenses count]];
    FOREACH(Expense *, exp, allExpenses) {
        NSDate *date = [exp date];
        NSString *dateStr = [date descriptionWithCalendarFormat:@"%Y-%m-%d" 
                                                       timeZone:nil 
                                                         locale:nil];
        id memo = [exp memo];
        if (memo == nil) memo = @"";
        NSString *serializedExpense = [NSString stringWithFormat:format, 
                                      dateStr, [exp amount], [exp payeeName],
                                      [[exp category] name], memo];
        [serializedExpenses addObject:serializedExpense];
    } ENDFOREACH;
    [serializedExpenses sortUsingSelector:@selector(compare:)];

    // Create a big string.
    [serializedExpenses insertObject:@"Date\tAmount\tPayee\tCategory\tComment"
                             atIndex:0];
    NSString *string = [NSString stringByJoining:serializedExpenses withString:@"\n"];
    
    // Try to write it to a file.
    NSError *error = nil;
    if (![string writeToFile:[savePanel filename]
                  atomically:NO
                    encoding:NSUTF8StringEncoding
                       error:&error]) 
    {
        [m_drachmaController presentError:error];
    }
}

@end
