//
//  ECImageRef.m
//  SceneRenderProto
//
//  Created by 二鏡 on 11/11/14.
//  Copyright 2011年 二鏡庵. All rights reserved.
//

#import "ECImageRef.h"

static NSString *plistImageURLKey = @"com.mac.nikyo-an.coding.ECImageRef.url";

@implementation ECImageRef

- (id)initWithURL:(NSURL*)aURL
{
    id opts = [NSDictionary dictionaryWithObjectsAndKeys:
               (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailWithTransform, 
               (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailFromImageIfAbsent,
               [NSNumber numberWithInt: 128],  kCGImageSourceThumbnailMaxPixelSize,
               nil];
    src = CGImageSourceCreateWithURL((CFURLRef)aURL, (CFDictionaryRef)opts);
    if(src == nil)
        return nil;

    url = [aURL copy];
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    url = [[aDecoder decodeObjectForKey: plistImageURLKey] copy];
    id opts = [NSDictionary dictionaryWithObjectsAndKeys:
               (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailWithTransform, 
               (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailFromImageIfAbsent,
               [NSNumber numberWithInt: 128],  kCGImageSourceThumbnailMaxPixelSize,
               nil];
    src = CGImageSourceCreateWithURL((CFURLRef)url, (CFDictionaryRef)opts);
    if(src == nil)
    {
        [url release];
        return nil;
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject: url forKey: plistImageURLKey];
}

- (void)dealloc
{
    if(src != nil)
        CFRelease(src);
    [url release];
    [super dealloc];
}

- (NSURL*)URL
{
    return url;
}

- (CGSize)imageSize
{
    if(src == nil)
        return CGSizeZero;
    CFDictionaryRef dic = CGImageSourceCopyPropertiesAtIndex(src, 0, nil);
    id width = CFDictionaryGetValue(dic,kCGImagePropertyPixelWidth);
    id height = CFDictionaryGetValue(dic,kCGImagePropertyPixelHeight);
    CGSize ret = CGSizeMake([width intValue], [height intValue]);
    CFRelease(dic);
    return ret;
}

- (CGImageRef)image
{
    CGImageRef image = CGImageSourceCreateImageAtIndex(src, 0, nil);
    [(id)image autorelease];
    return image;
}

- (CGImageRef)thumbnail
{
    CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, nil);
    [(id)thumbnail autorelease];
    return thumbnail;
}

@end
