//
// Copyright (c) 2020 iRidge,Inc. All rights reserved.
//

#import <sys/sysctl.h>
#import <UIKit/UIKit.h>
#import "PopinfoWebkitUtil.h"
#import "PopinfoReceiver.h"

static NSString *const webExtVersion = @"3.0.0";

@implementation PopinfoWebkitUtil {

}

+ (BOOL)receiveJavaScriptMessage:(WKScriptMessage *)message onWebView:(WKWebView *)webView
{
    NSString *command = message.body[@"command"];

    if ([command compare:@"trackEvent"] == NSOrderedSame) {

        NSData *data = [message.body[@"parameters"] dataUsingEncoding:NSUTF8StringEncoding];

        NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data
                                                            options:NSJSONReadingFragmentsAllowed error:nil];

        [[PopinfoReceiver sharedReceiver] trackEventUnsafe:message.body[@"name"] value:dic];

        return YES;
    }

    if ([command compare:@"getEnvInfo"] == NSOrderedSame) {

        NSString *script = [NSString stringWithFormat:@"%@(\"{\\\"webExtVersion\\\":\\\"%@\\\",\\\"sdkVersion\\\":\\\"%@\\\",\\\"deviceType\\\":\\\"iphone\\\",\\\"osVersion\\\":\\\"%@\\\"}\");",
                message.body[@"callback"], webExtVersion, [[PopinfoReceiver sharedReceiver] sdkVersion], [UIDevice currentDevice].systemVersion
        ];

        [webView evaluateJavaScript:script completionHandler:nil];

        return YES;
    }

    return NO;
}

@end
