
#import "ABJSWrapper.h"

#define APPBORG_WEBVIEW_SAMPLE_MS   10

@implementation ABJSWrapper


- (id)initWithRouter:(ABRouter*)router name:(NSString*)name webView:(WebView*)webView
{
    self = [super init];
    if (self) {
        _router = [router retain];
        _name = [name retain];
        _webView = [webView retain];
        _jsonParser = [[[SBJsonParser alloc] init] retain];
        
        [router _registerComponent:self];
        
        [NSTimer
             scheduledTimerWithTimeInterval:(APPBORG_WEBVIEW_SAMPLE_MS / 1000.0)
             target:self
             selector:@selector(_pollWebView:)
             userInfo:nil
             repeats:YES];
    }
    return self;
}


- (NSString*) _getName
{
    return _name;
}


- (void) _sendEventJson:(NSString *)json
{
    [self _pollWebViewPushingEventJson:json];
}

- (void) _pollWebView:(NSTimer*)timer
{
    [self _pollWebViewPushingEventJson:@""];
}

- (void) _pollWebViewPushingEventJson:(NSString *)eventJson
{
    NSString *result = [_webView stringByEvaluatingJavaScriptFromString:
                                    [NSString stringWithFormat:
                                        @"appborg.pushAndPullEvents([%@])", eventJson]];
    
    // result is a JSON string: @"[...]"
    if ([result length] > 2) {
        NSArray *events = [_jsonParser objectWithString:result];
        for (NSDictionary *event in events) {
            [_router _processEvent:event];
        }
    }
}


- (void)dealloc
{
    [_router release];
    [_name release];
    [_webView release];
}

@end
