//
//  ECTextImporterController.m
//  Etokicho
//
//  Created by 二鏡 on 11/11/28.
//  Copyright 2011年 二鏡庵. All rights reserved.
//

#import "ECTextImporterController.h"

static id _si = nil;

@implementation ECTextImporterController
@synthesize selectedIndex;
+ (id)sharedTextImporter
{
    if(_si == nil)
    {
        _si = [[self alloc] initWithWindowNibName: @"TextImporter"];
        [_si window];
    }
    return _si;
}

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        lines = [[NSMutableArray alloc] init];
    }
    
    return self;
}

- (void)awakeFromNib
{
    [list setDoubleAction: @selector(insertItem:)];
    [list setTarget: self];
    id types = [NSArray arrayWithObjects: (id)kUTTypeFileURL, NSPasteboardTypeString, nil];
    [list registerForDraggedTypes: types];
    [self setWindowFrameAutosaveName: @"TextImporterWindowFrame"];
}

- (NSArray*)splitString:(NSString*)aString
{
    // 行分割のテンプレ処理
    id ret = [NSMutableArray array];
    id br = [NSCharacterSet newlineCharacterSet];
    id scanner = [NSScanner scannerWithString: aString];
    
    while([scanner isAtEnd] == NO)
    {
        // 改行に当たるまで読み込んで
        id buf;
        if([scanner scanUpToCharactersFromSet: br
                                   intoString: &buf])
        {
            [ret addObject: buf];
        }
        
        // 改行が出る限り捨てる
        [scanner scanCharactersFromSet: br intoString: nil];
    }
    
    return [[ret copy] autorelease];
}

- (void)_loadString:(NSString*)string
{
    [self willChangeValueForKey: @"lines"];
    [lines release];
    lines = [[self splitString: string] mutableCopy];
    [self didChangeValueForKey: @"lines"];
}

- (void)loadPlainText:(NSURL*)URL
{
    NSStringEncoding encoding;
    id error;
    id string = [NSString stringWithContentsOfURL:URL
                                     usedEncoding: &encoding
                                            error: &error];
    if(string == nil)
    {
        [NSApp presentError: error];
        return ;
    }
    
    [self _loadString: string];
}

- (void)loadRTF:(NSURL*)URL
{
    id dic;
    id aStr = [[[NSAttributedString alloc] initWithURL: URL
                                    documentAttributes: &dic] autorelease];
    [self _loadString: [aStr string]];
}

- (IBAction)insertItem:(id)sender
{
    id obj = [proxy selection];
    id val = [[controller selection] valueForKey: @"self"];
    [obj setValue: val forKey: @"string"];
}

- (IBAction)import:(id)sender
{
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowedFileTypes: [NSArray arrayWithObjects:(id)kUTTypePlainText,(id)kUTTypeRTF, nil]];
    [panel setExtensionHidden: YES];

    [panel beginSheetModalForWindow: [self window]
                  completionHandler: ^(NSInteger result) 
     {
         if(result != NSFileHandlingPanelOKButton)
             return;
         id URL = [panel URL];
         
         id ws = [NSWorkspace sharedWorkspace];
         id error;
         CFStringRef type = (CFStringRef)[ws typeOfFile: [URL path] error: &error];
         if(type)
         {
             if(UTTypeConformsTo(type, kUTTypePlainText))
             {
                 [self loadPlainText: URL];
             }
             else
             {
                 [self loadRTF: URL];
             }
         }
     }];
}

- (NSDragOperation)tableView:(NSTableView *)aTableView
                validateDrop:(id < NSDraggingInfo >)info
                 proposedRow:(NSInteger)row
       proposedDropOperation:(NSTableViewDropOperation)operation
{
    id error;
    
    id pboard = [info draggingPasteboard];
    id types = [NSArray arrayWithObjects: (id)kUTTypeFileURL, NSPasteboardTypeString, nil];
    CFStringRef draggingType = (CFStringRef)[pboard availableTypeFromArray: types];
    if(draggingType == nil)
        return NSDragOperationNone;
    
    if(UTTypeConformsTo(draggingType, kUTTypeFileURL))
    {
        id url = [NSURL URLFromPasteboard: pboard];
        id ws = [NSWorkspace sharedWorkspace];
        CFStringRef type = (CFStringRef)[ws typeOfFile: [url path] error: &error];
        if(type == nil)
            return NSDragOperationNone;
        
        if(UTTypeConformsTo(type, kUTTypePlainText) ||
           UTTypeConformsTo(type, kUTTypeRTF))
            return NSDragOperationEvery;
        else
            return NSDragOperationNone;
    }
    else
    {
        return NSDragOperationEvery;
    }
}

- (BOOL)tableView:(NSTableView *)aTableView
       acceptDrop:(id < NSDraggingInfo >)info
              row:(NSInteger)row
    dropOperation:(NSTableViewDropOperation)operation
{
    id error;
    id pboard = [info draggingPasteboard];
    id types = [NSArray arrayWithObjects: (id)kUTTypeFileURL, NSPasteboardTypeString, nil];
    CFStringRef draggingType = (CFStringRef)[pboard availableTypeFromArray: types];
    
    if(UTTypeConformsTo(draggingType, kUTTypeFileURL))
    {
        id url = [NSURL URLFromPasteboard: pboard];
        id ws = [NSWorkspace sharedWorkspace];
        CFStringRef type = (CFStringRef)[ws typeOfFile: [url path] error: &error];
        
        if(UTTypeConformsTo(type, kUTTypePlainText))
            [self loadPlainText: url];
        else
            [self loadRTF: url];
    }
    else
    {
        [self _loadString: [pboard stringForType: (id)draggingType]];
    }
    return YES;
}

- (NSString*)tableToolTip
{
    return NSLocalizedString(@"Drop a file or text content to split it.", @"");
}
@end
