//
//  ECTimelineManager+Service.m
//  Etokicho
//
//  Created by 二鏡 on 11/12/07.
//  Copyright (c) 2011年 二鏡庵. All rights reserved.
//

#import "ECTimelineManager.h"
#import "ECDSceneSegment.h"
#import "ECDTransitionSegment.h"

@implementation ECTimelineManager (Service)
- (NSArray*)aroundScenesOfSelectedSegment
{
    if([selection count] != 1)
        return nil;
    NSUInteger idx = [selection firstIndex];
    id segments = [timeline segments];
    id first,second;
    if(idx == 0)
        first = NSNotApplicableMarker;
    else
        first = [segments objectAtIndex: idx-1];
    if(idx == [segments count]-1)
        second = NSNotApplicableMarker;
    else
        second = [segments objectAtIndex: idx+1];
    if([first isKindOfClass: [ECDSceneSegment class]] == NO)
        first = NSNotApplicableMarker;
    if([second isKindOfClass: [ECDSceneSegment class]] == NO)
        second = NSNotApplicableMarker;
    return [NSArray arrayWithObjects: first, second, nil];
}

- (ECScene*)posterScene
{
    id segments = [[timeline segments] array];
    id revIter = [segments reverseObjectEnumerator];
    for(id seg in revIter)
    {
        if([seg isKindOfClass: [ECDSceneSegment class]])
            return [[[seg scene] copy] autorelease];
    }
    
    return nil;
}

- (NSString*)totalTimeString
{
    id segments = [[timeline segments] array];
    NSUInteger msec = 0;
    for(ECDSegment *seg in segments)
        msec += seg.msec;
    
    NSUInteger sec = msec / 1000;
    NSUInteger _min = sec / 60;
    NSUInteger _sec = sec % 60;
    NSUInteger _msec = msec % 1000;
    
    id fmt = NSLocalizedString(@"%lumin %lusec %lumsec",@"");
    return [NSString stringWithFormat: fmt, _min, _sec, _msec];
}

- (NSArray*)segmentsOfObjectIDURIs:(NSArray*)URIs
{
    id coord = [context persistentStoreCoordinator];
    id ret = [NSMutableArray array];
    for(id URI in URIs)
    {
        id objectID = [coord managedObjectIDForURIRepresentation: URI];
        id obj = [context objectWithID: objectID];
        if(obj != nil)
            [ret addObject: obj]; // 既に存在しないオブジェクトかも知れない！
    }
    
    return [[ret copy] autorelease];
}

- (NSArray*)cloneSegments:(NSArray*)segments
{
    id ret = [NSMutableArray array];
    for(ECDSegment *seg in segments)
    {
        [ret addObject: [seg cloneInContext: context]];
    }
    
    return [[ret copy] autorelease];
}
@end                    
