//
//  MigrateConnController.h
//  Flash2
//
//  Copyright 2008 Nicholas Matsakis. 
//  The code in thie file is released to the public under the
//  terms of the MIT License as described here:
//  http://www.opensource.org/licenses/mit-license.php
//

#import "MigrateConnController.h"
#import "OxNSNumber.h"
#import "OxNSArray.h"
#import "WordTextFieldDelegate.h"

@implementation MigrateConnController

@synthesize existingConnections = a_existingConnections;

NSMutableDictionary *ConnInfo(NSImage *direction, Connection *conn) {
    // XXX check that the connection CAN be legally migrated!
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            [NSNumber numberWithYES], @"migrate",
            conn, @"connection",
            conn.fromWord, @"fromWord",
            direction, @"direction",
            conn.type.name, @"relationshipName",
            conn.toWord, @"toWord",
            nil];
}

- initWithFromWord:(Word*)fromWord 
            toWord:(Word*)toWord
      parentWindow:(NSWindow*)parentWindow
          delegate:(id)delegate
{
    if ((self = [super initWithWindowNibName:@"MigrateConn"])) {
        m_fromWord = fromWord;
        m_toWord = toWord;
        m_delegate = delegate;
        m_parentWindow = parentWindow;
        
        NSMutableArray *existingConnections = [NSMutableArray array];
        
        NSImage *fromDirection = [NSImage imageNamed:@"NSGoLeftTemplate"];
        for (Connection *conn in fromWord.connectionsFrom)
            [existingConnections addObject:ConnInfo(fromDirection, conn)];

        NSImage *toDirection = [NSImage imageNamed:@"NSGoRightTemplate"];
        for (Connection *conn in fromWord.connectionsTo)
            [existingConnections addObject:ConnInfo(toDirection, conn)];
        
        self.existingConnections = existingConnections;
    }
    return self;
}

- (void) activate 
{
    [NSApp beginSheet:[self window]
       modalForWindow:m_parentWindow
        modalDelegate:self
       didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) // optional
          contextInfo:nil];
}

- (IBAction) migrate:(id)sender
{
    [NSApp endSheet:[self window] returnCode:1];
}

- (IBAction) migrateNone:(id)sender
{
    [NSApp endSheet:[self window] returnCode:0];
}

- (void) sheetDidEnd:(NSWindow *)sheet 
          returnCode:(int)ok
         contextInfo:(void *)contextInfo
{
    [[self window] orderOut:self];
    NSArray *connections;
    if (ok) {
        NSArray *toMigrate = [[self.existingConnections filter] valueForKey:@"migrate"];
        connections = [[toMigrate map] valueForKey:@"connection"];
    } else {
        connections = [NSArray array];
    }
    [m_delegate migrateConnections:connections toWord:m_toWord];
}

@end
