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

#ifndef Etokicho_ServiceFunctions_h
#define Etokicho_ServiceFunctions_h

#import <Cocoa/Cocoa.h>


static inline NSSize
_sizeFromData(NSData *data)
{
    return [[NSUnarchiver unarchiveObjectWithData: data] sizeValue];
}

static inline NSData *
_sizeToData(NSSize size)
{
    return [NSArchiver archivedDataWithRootObject: [NSValue valueWithSize: size]];
}

static inline NSPoint
_pointFromData(NSData *data)
{
    return [[NSUnarchiver unarchiveObjectWithData: data] pointValue];
}

static inline NSData *
_pointToData(NSPoint point)
{
    return [NSArchiver archivedDataWithRootObject: [NSValue valueWithPoint: point]];
}

static inline NSRect
_rectFromData(NSData *data)
{
    return [[NSUnarchiver unarchiveObjectWithData: data] rectValue];
}

static inline NSData *
_rectToData(NSRect rect)
{
    return [NSArchiver archivedDataWithRootObject: [NSValue valueWithRect: rect]];
}

static inline CGColorRef
_cgcolorRGBFromData(NSData *data)
{
    const CGFloat *rgba = [data bytes];
    return CGColorCreateGenericRGB(rgba[0], rgba[1], rgba[2], rgba[3]);
}

static inline NSData*
_cgcolorRGBToData(CGColorRef color)
{
    const CGFloat *rgba = CGColorGetComponents(color);
    return [NSData dataWithBytes: rgba length: sizeof(CGFloat)*4];
}

static void
_calculateFrameInfo(NSUInteger fps, 
                    NSUInteger msec, 
                    NSUInteger *o_f_sec,  // 1フレームの基本m秒数
                    NSUInteger *o_frames, // 総フレーム数
                    NSUInteger *o_adjust_cycle) // 秒数補正フレームのサイクル
{
    NSUInteger f_sec = 1000/fps;
    NSUInteger frames = msec/f_sec;
    NSUInteger remain = msec-f_sec*frames;
    NSUInteger adjust_cycle = remain != 0 ? frames/remain : frames+1;
    
    *o_f_sec = f_sec;
    *o_frames = frames;
    *o_adjust_cycle = adjust_cycle;
}
#endif
