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

#import "DirectoryObserver.h"

NSString *DictoryObserverFolderUpdateNotification = @"DictoryObserverFolderUpdate";

@interface DirectoryObserver()
- (void)postNotification;
@end

static
void _subscriptionProc(FNMessage msg,
                       OptionBits lfags,
                       id observer,
                       FNSubscriptionRef sub)
{
    [observer postNotification];
}

// 何処を監視しているかはobserverで特定できないとダメ。
static FNSubscriptionUPP _callback;

@implementation DirectoryObserver

+ (void)initialize
{
    _callback = NewFNSubscriptionUPP(_subscriptionProc);
}

- (id)initWithTarget:(NSString*)folder
{
    target = [folder copy];
    return self;
}

- (void)dealloc
{
    [target release];
    [super dealloc];
}

- (void)start
{
    // パスの変換で出来上がり
    const UInt8 *path = (const UInt8*)[target UTF8String];
    FNSubscribeByPath(path, _callback, self, kNilOptions, &info);
}

- (void)stop
{
    FNUnsubscribe(info);
}

- (void)postNotification
{
    id ui = [NSDictionary dictionaryWithObject: target
                                        forKey: @"Folder"];
    [[NSNotificationCenter defaultCenter]
     postNotificationName: DictoryObserverFolderUpdateNotification
     object: self
     userInfo: ui];
}
@end
