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

#import "ECTemplateSourceImageView.h"
#import "ECScene.h"

@implementation ECTemplateSourceImageView

- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
{
    return YES;
}

- (void)mouseDown:(NSEvent*)theEvent
{
    id scene = [[sceneController selection] valueForKey: @"scene"];
    if(scene == nil)
        return ;
    
    NSPoint location;
    NSRect rect;
    id types = [NSArray arrayWithObject: gSceneFileExtension];
    
    location = [self convertPoint: [theEvent locationInWindow]
                         fromView: nil];
    
    location.x -= 16.0;
    location.y -= 16.0;
    rect.origin = location;
    rect.size = NSMakeSize(64,64);
    
    [self dragPromisedFilesOfTypes: types
                          fromRect: rect
                            source: self
                         slideBack: YES
                             event: theEvent];
}

- (void)draggingSession:(NSDraggingSession *)session
           endedAtPoint:(NSPoint)screenPoint
              operation:(NSDragOperation)operation
{
    if(path == nil)
        return; // cancel
    
    id url = [NSURL fileURLWithPath: path];
    id scene = [[sceneController selection] valueForKey: @"scene"];
    [scene writeToURL: url];
    [path release];
    path = nil;
}

- (NSArray*)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
{
    id name, fullpath;
    id fm = [NSFileManager defaultManager];
    name = [ECScene templateName0];
    fullpath = [[dropDestination URLByAppendingPathComponent: name] path];
    if([fm fileExistsAtPath: fullpath] == NO)
    {
        path = [fullpath retain];
        return [NSArray arrayWithObject: name];
    }
    
    for(int i=1;;i++)
    {
        name = [ECScene templateNameWithCount: i];
        fullpath = [[dropDestination URLByAppendingPathComponent: name] path];
        if([fm fileExistsAtPath: fullpath])
            continue;
        
        path = [fullpath retain];
        break;
    }
    return [NSArray arrayWithObject: name];
}
@end
