//
//  QuickSDKCocos_ios.m
//  QuickSDKInterfaceCocos
//
//  Created by 0280106PC0119 on 15/9/8.
//  Copyright (c) 2015年 QuickSDK. All rights reserved.
//

#import "QuickSDK_ios.h"
#import "QuickSDKInterfaceUnity.h"


#if defined(__cplusplus)
extern "C"{
#endif
    extern void UnitySendMessage(const char *, const char *, const char *);
#if defined(__cplusplus)
}
#endif

@implementation QuickSDK_ios

static QuickSDK_ios * __singleton__;
+ (QuickSDK_ios *)shareInstance {
    static dispatch_once_t predicate;
    dispatch_once( &predicate, ^{ __singleton__ = [[[self class] alloc] init]; } );
    return __singleton__;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self addNotifications];
        initState = -1;
        bU3dInited = NO;
    }
    return self;
}

-(void)addNotifications
{
    static BOOL isAdded = NO;
    if (isAdded) {
        return;
    }
    isAdded = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initResult:) name:kSmpcQuickSDKNotiInitDidFinished object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginResult:) name:kSmpcQuickSDKNotiLogin object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutResult:) name:kSmpcQuickSDKNotiLogout object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rechargeResult:) name:kSmpcQuickSDKNotiRecharge object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(realNameAuthResult:) name:kSmpcQuickSDKNotiRealAuth object:nil];

}

- (NSString *)jsonStrFromDictionary:(NSDictionary *)dic {
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
    if ([error code]) {
        return @"";
    }
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

-(void)sendU3dMessage:(NSString *)messageName :(NSDictionary *)dict
{
    if (dict != nil)
    {
        NSString *jsonString = [self jsonStrFromDictionary:dict];
//        char *gameObjectNameCStr = (char *)malloc(100);
//        strcpy(gameObjectNameCStr, [_gameObjectName UTF8String]);
//        char *messageNameCStr = (char *)malloc(100);
//        strcpy(messageNameCStr, [messageName UTF8String]);
//        char *jsonStringCStr = (char *)malloc(1000);
//        strcpy(jsonStringCStr, [jsonString UTF8String]);
//        UnitySendMessage(gameObjectNameCStr, messageNameCStr, jsonStringCStr);
        UnitySendMessage([_gameObjectName UTF8String], [messageName UTF8String], [jsonString UTF8String]);
    }
    else{
//        char *gameObjectNameCStr = (char *)malloc(100);
//        strcpy(gameObjectNameCStr, [_gameObjectName UTF8String]);
//        char *messageNameCStr = (char *)malloc(100);
//        strcpy(messageNameCStr, [messageName UTF8String]);
//        UnitySendMessage(gameObjectNameCStr, messageNameCStr, "");
        UnitySendMessage([_gameObjectName UTF8String], [messageName UTF8String], "");
    }
}

- (void)setListener:(NSString *)gameObjectName
{
    _gameObjectName = gameObjectName;
#if !__has_feature(objc_arc)
    _gameObjectName = [gameObjectName retain];
#endif
    bU3dInited = YES;
    //在此时发消息回去才能保证u3d加载好了，可以接收初始化消息了
    if (initState == -1)//未初始化
    {
        ;
    }
    else if (initState == 0)//初始化失败
    {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"init failed", @"msg", nil];
        [self sendU3dMessage:@"onInitFailed" :dic];
        initState = -1;
    }
    else if (initState == 1)//初始化成功
    {
        [self sendU3dMessage:@"onInitSuccess" :nil];
        initState = -1;
    }
    
}

-(void)login
{
    [[SMPCQuickSDK defaultInstance] login];
}
-(void)logout
{
    [[SMPCQuickSDK defaultInstance] logout];
}

-(void)pay:(SMPCQuickSDKPayOrderInfo *)orderInfo gameRoleInfo:(SMPCQuickSDKGameRoleInfo *)gameRoleInfo
{
    [[SMPCQuickSDK defaultInstance] payOrderInfo:orderInfo roleInfo:gameRoleInfo];
}
-(void)Getlocalized:(NSString *)productIds
{
    [[SMPCQuickSDK defaultInstance] Getlocalized:productIds];
}
- (void)updateRoleInfoWith:(SMPCQuickSDKGameRoleInfo *)gameRoleInfo
{
    [[SMPCQuickSDK defaultInstance] updateRoleInfoWith:gameRoleInfo];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:gameRoleInfo.serverId,@"serverId", gameRoleInfo.serverName,@"serverName",gameRoleInfo.gameRoleName,@"gameRoleName",gameRoleInfo.gameRoleID,@"gameRoleId",gameRoleInfo.gameUserBalance,@"gameUserBalance",
                         gameRoleInfo.vipLevel,@"vipLevel",gameRoleInfo.gameUserLevel,@"gameUserLevel",gameRoleInfo.partyName,@"partyName",nil];
    [self sendU3dMessage:@"onUpdateRoleInfoSuccess" :dic];
}
-(void)updateRoleInfoWith:(SMPCQuickSDKGameRoleInfo *)gameRoleInfo isCreate:(BOOL)isCreate{
    [[SMPCQuickSDK defaultInstance] updateRoleInfoWith:gameRoleInfo isCreate:isCreate];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:gameRoleInfo.serverId,@"serverId", gameRoleInfo.serverName,@"serverName",gameRoleInfo.gameRoleName,@"gameRoleName",gameRoleInfo.gameRoleID,@"gameRoleId",gameRoleInfo.gameUserBalance,@"gameUserBalance",
                         gameRoleInfo.vipLevel,@"vipLevel",gameRoleInfo.gameUserLevel,@"gameUserLevel",gameRoleInfo.partyName,@"partyName",nil];
    [self sendU3dMessage:@"onUpdateRoleInfoSuccess" :dic];
}
-(void)enterYunKeFuCenter:(SMPCQuickSDKGameRoleInfo *)gameRoleInfo
{
    [[SMPCQuickSDK defaultInstance] enterYunKeFuCenter:gameRoleInfo];
}
- (int)enterUserCenter
{
    return [[SMPCQuickSDK defaultInstance] enterUserCenter];
}

-(void)openThirdLogin:(BOOL)thirdLogin
{
}

- (NSString *)getIdCode
{
}

-(BOOL)isGuester
{
     return NO;
}

-(void)ShowCertification
{
}

-(void) BindCertification;
{
}
- (int)enterCustomerCenter
{
    return 0;
}
- (int)enterBBS
{
    return 0;
}
- (int)showRealNameAuth:(int)show {
    NSDictionary * dict = [[SMPCQuickSDK defaultInstance] realNameInfo];
    if ([dict[kSmpcQuickSDKKeyRealName] boolValue]) {
        [self sendU3dMessage:@"realAuthSuccess" :dict];
        return 0;
    }
    return show ? [[SMPCQuickSDK defaultInstance] realAuth]:0;
}
- (int)showToolBar:(int)place
{
    return [[SMPCQuickSDK defaultInstance] showToolBar:(SMPC_QUICK_SDK_TOOLBAR_PLACE)place];
}
- (int)hideToolBar
{
    return [[SMPCQuickSDK defaultInstance] hideToolBar];
}
-(int)pausedGame
{
    return 0;
}
- (bool)isFunctionTypeSupported:(int)type
{
    if (type == 8) {
        NSDictionary * dict = [[SMPCQuickSDK defaultInstance] realNameInfo];
        if ([dict[kSmpcQuickSDKKeyRealName] boolValue]) {
            [self sendU3dMessage:@"realAuthSuccess" :dict];
            return YES;
        }
    }
    return [[SMPCQuickSDK defaultInstance] isFunctionTypeSupported:(SMPC_QUICK_SDK_FUNC_TYPE)type];
}
- (NSString *)channelName          //获取渠道名称
{
    return @"";
}
- (NSString *)channelVersion       //获取渠道版本
{
    return @"";
}
- (int)channelType                 //获取渠道类别 渠道唯一标识
{
    return [[SMPCQuickSDK defaultInstance] channelType];
}
- (NSString *)userId
{
    return [[SMPCQuickSDK defaultInstance] userId];
}
- (NSString *)userToken{
    return [[SMPCQuickSDK defaultInstance] userToken];
}
- (NSString *)SDKVersion      //QuickSDK版本
{
    return @"";
}
- (NSString *)getConfigValue:(NSString *)key      //QuickSDK版本
{
    return [[SMPCQuickSDK defaultInstance] getConfigValue:key];
}


#pragma call back
- (void)realNameAuthResult:(NSNotification *)notify {
    [self sendU3dMessage:@"realAuthSuccess" :notify.userInfo];
}
-(void)initResult:(NSNotification *)notify
{
    NSDictionary *userInfo = notify.userInfo;
    int errorCode = [userInfo[kSmpcQuickSDKKeyError] intValue];
    switch (errorCode) {
        case SMPC_QUICK_SDK_ERROR_NONE:
        {
            if (bU3dInited)
            {
                [self sendU3dMessage:@"onInitSuccess" :nil];
            }
            else
            {
                initState = 1;
            }
        }
            break;
        case SMPC_QUICK_SDK_ERROR_INIT_FAILED:
        default:
        {
            if (bU3dInited)
            {
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"init failed", @"msg", nil];
                [self sendU3dMessage:@"onInitFailed" :dic];
            }
            else
            {
                initState = 0;
            }
        }
            break;
    }
}

-(void)loginResult:(NSNotification *)notify
{
    NSDictionary *rDic = [notify userInfo];
    if ([rDic[kSmpcQuickSDKKeyError] intValue] == 0) {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:rDic[@"uid"],@"userId", rDic[@"user_token"], @"userToken", rDic[@"user_name"], @"userName", @"", @"msg", nil];
        [self sendU3dMessage:@"onLoginSuccess" :dic];
    }else{
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:rDic[kSmpcQuickSDKKeyMsg],@"msg", nil];
        [self sendU3dMessage:@"onLoginFailed" :dic];
    }
}

-(void)logoutResult:(NSNotification *)notify
{
    NSDictionary *rDic = [notify userInfo];
    if ([rDic[kSmpcQuickSDKKeyError] intValue] == 0) {
        [self sendU3dMessage:@"onLogoutSuccess" :nil];
    }else{
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:rDic[kSmpcQuickSDKKeyMsg],@"msg", nil];
        [self sendU3dMessage:@"onLogoutFailed" :dic];
    }
}

-(void)rechargeResult:(NSNotification *)notify
{
    NSDictionary *rDic = [notify userInfo];
    if ([rDic[kSmpcQuickSDKKeyError] intValue] == 0) {
        
        NSLog(@"---------------%@", rDic); 
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:rDic[kSmpcQuickSDKKeyOrderId],kSmpcQuickSDKKeyOrderId,rDic[kSmpcQuickSDKKeyCpOrderId],kSmpcQuickSDKKeyCpOrderId, nil];
        [self sendU3dMessage:@"onPaySuccess" :dic];
    }else if ([rDic[kSmpcQuickSDKKeyError] intValue] == SMPC_QUICK_SDK_ERROR_RECHARGE_CANCELLED){
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:rDic[kSmpcQuickSDKKeyCpOrderId],kSmpcQuickSDKKeyCpOrderId, nil];
        [self sendU3dMessage:@"onPayCancel" :dic];
    } else {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:rDic[kSmpcQuickSDKKeyCpOrderId],kSmpcQuickSDKKeyCpOrderId, nil];
        [self sendU3dMessage:@"onPayFailed" :dic];
    }
}
@end
