//
//  UniversalSDK.m
//  Unity-iPhone
//
//  Created by 蔡瀚 on 2018/4/24.
//

#import "UniversalSDK.h"
#import "AdSupport/AdSupport.h"
#import "opus.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "SystemConfiguration/CaptiveNetwork.h"
#import <SMPCQuickSDK/SMPCQuickSDK.h>

@interface UniversalSDK()<UIWebViewDelegate>
@end

@implementation UniversalSDK

#define CHANNEL_NUM 1

static int s_frequency = 16000;
static int s_bitRate = 20000;
static int s_bandMode = OPUS_BANDWIDTH_WIDEBAND;
static int s_frameSize = 160;
static int sBatteryLevel = -1;
static int sBatteryState = -1;
static NSString* sAppID;
static NSString* sGameID;
static NSString* sUserName;
static NSThread* _thread;

-(void) Init
{
    UIDevice *_device = [UIDevice currentDevice];
    _device.batteryMonitoringEnabled = true;
    
    NSString* _uniqueID = [[NSUserDefaults standardUserDefaults] objectForKey:@"tsw_unique_id"];
    //获取IDFA
    NSString* _idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    if(_uniqueID == NULL || [_uniqueID length] <= 0)
    {
        //判断IDFA是否为空
        BOOL isEmpty = [[_idfa stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByReplacingOccurrencesOfString:@"0" withString:@""].length;
        if (isEmpty) {
            //不为空，将IDFA作为唯一标识
            _uniqueID = _idfa;
        }
        else {
            //为空，获取UUID作为唯一标识
            _uniqueID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        }
        
        //保存唯一设备标识,如已存在则不进行任何处理
        [[NSUserDefaults standardUserDefaults] setObject:_uniqueID forKey:@"tsw_unique_id"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    // 取得UserAgent
    UIWebView* _webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString* _userAgent = [_webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    
    // 发送设备信息
    NSMutableDictionary *_dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                  _uniqueID,@"unique_id",
                                  _idfa,@"android_id",
                                  [NSNumber numberWithInt:S2U_DeviceInfo],@"code",
                                  _userAgent,@"userAgent",nil];
    [self SendMessageToUnity:_dict];
}

-(void)SendMessageToUnity:(NSDictionary*)dict
{
    BOOL _result = [NSJSONSerialization isValidJSONObject:dict];
    if(_result)
    {
        NSData* _jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
        UnitySendMessage(UNITY_OBJ_NAME, UNITY_FUNC_NAME,
                         [[[NSString alloc] initWithData:_jsonData encoding:NSUTF8StringEncoding] UTF8String]);
    }
}

-(void) BatteryThread {
    while (TRUE)
    {
        [NSThread sleepForTimeInterval:1];
        
        UIDevice *_device = [UIDevice currentDevice];
        
        int _state = [_device batteryState];
        if(_state != sBatteryState){
            sBatteryState = _state;
            NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [NSNumber numberWithInt:sBatteryState], @"status",
                                   [NSNumber numberWithInt:S2U_BatteryCharging], @"code", nil];
            
            [self SendMessageToUnity:_dict];
        }
        
        int _level = (int)([_device batteryLevel] * 100);
        if(_level != sBatteryLevel){
            sBatteryLevel = _level;
            NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [NSNumber numberWithInt:sBatteryLevel], @"level",
                                   [NSNumber numberWithInt:S2U_BatteryLevel], @"code", nil];
            
            [self SendMessageToUnity:_dict];
        }
    }
}

-(void) OpenURL:(NSString*) url {
    
    if(m_UIWebView != NULL) {
        [self btnClick:NULL];
        return;
    }
    
    CGRect _bounds = UnityGetMainWindow().bounds;
    
    float _scale = _bounds.size.width / 1334;
    
    float _width = 982 * _scale;
    float _height = 560 * _scale;
    
    float _offsetX = (_bounds.size.width - _width) * .5f;
    float _offsetY = (_bounds.size.height - _height) * .5f;
    
    m_UIWebView = [[UIWebView alloc] initWithFrame:CGRectMake(_offsetX, _offsetY, _width, _height)];
    m_UIWebView.delegate = self;
    m_UIWebView.scalesPageToFit = YES ;
    m_UIWebView.scrollView.scrollEnabled = YES;
    m_UIWebView.scrollView.bounces = NO;
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [m_UIWebView loadRequest:request];
}

-(void) btnClick:(UIButton*)sender {
    [m_CloseBtn removeFromSuperview];
    [m_CloseBtn removeTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    m_CloseBtn = NULL;
    
    NSURLCache *_cache = [NSURLCache sharedURLCache];
    [_cache removeAllCachedResponses];
    [_cache setDiskCapacity:0];
    [_cache setMemoryCapacity:0];
    
    [m_UIWebView removeFromSuperview];
    m_UIWebView = NULL;
}

-(void)webViewDidStartLoad:(UIWebView *)webView{
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    
    [UnityGetMainWindow().rootViewController.view addSubview:m_UIWebView];
    CGRect _bounds = UnityGetMainWindow().bounds;
    
    float _scale = _bounds.size.width / 1334;
    
    float _width = 982 * _scale;
    float _height = 560 * _scale;
    
    m_CloseBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [m_CloseBtn setFrame:CGRectMake(_width - 455 * _scale, _height - 86 * _scale, 180 * _scale, 72 * _scale)];
    [m_CloseBtn setTitle:@"我知道了" forState:UIControlStateNormal];
    
    NSString *_bundlePath = [[NSBundle mainBundle] pathForResource:@"The2thWorldRES.bundle" ofType:nil];
    NSBundle *_bundle = [NSBundle bundleWithPath:_bundlePath];
    NSString *pic1Path = [_bundle pathForResource:@"TY_AN_34.png" ofType:nil];
    
    [m_CloseBtn setBackgroundImage:[UIImage imageWithContentsOfFile:pic1Path] forState:UIControlStateNormal];
    [m_CloseBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [m_CloseBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [m_UIWebView addSubview:m_CloseBtn];
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
}

-(void)QuickSDKInit:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 监听初始化
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(smpcQpInitResult:)
                                                 name:kSmpcQuickSDKNotiInitDidFinished
                                               object:nil];
    // 监听登录
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(smpcQpLoginResult:) name:kSmpcQuickSDKNotiLogin object:nil];
    // 监听注销
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(smpcQpLogoutResult:) name:kSmpcQuickSDKNotiLogout object:nil];
    // 监听充值结果
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(smpcQpRechargeResult:) name:kSmpcQuickSDKNotiRecharge object:nil];
    
    // --------------------- 初始化 --------------------------
    SMPCQuickSDKInitConfigure *cfg = [[SMPCQuickSDKInitConfigure alloc] init];
    cfg.productKey = PRODUCT_KEY;
    cfg.productCode = PRODUCT_CODE;
    [[SMPCQuickSDK defaultInstance] initWithConfig:cfg application:application didFinishLaunchingWithOptions:launchOptions];
    // ------------------------------------------------------
}

- (void)smpcQpInitResult:(NSNotification *)notify {
    NSLog(@"init result:%@",notify);
    NSDictionary *userInfo = notify.userInfo;
    int errorCode = [userInfo[kSmpcQuickSDKKeyError] intValue];
    switch (errorCode) {
        case SMPC_QUICK_SDK_ERROR_NONE:
        {
            NSLog(@"初始化成功");
//            NSString *_appid = [[SMPCQuickSDK defaultInstance] getConfigValue:@"zfappid"];
//            if (_appid == nil || [_appid isEqualToString:@""])
//            {
//                _appid = sAppID;
//            }
            NSString *_appid = sAppID;
            NSLog(@"init _appid:%@",_appid);
            
            NSMutableDictionary *_dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                          [NSNumber numberWithInt:S2U_SdkInitComplete], @"code",
                                          @"quick", @"channelPlatform",
                                          _appid, @"yj_appid", _appid, @"yj_spid", nil];
            [self SendMessageToUnity:_dict];
        }
            break;
        case SMPC_QUICK_SDK_ERROR_INIT_FAILED:
        default:
        {
            //初始化失败
            NSLog(@"渠道初始化失败");
        }
            break;
    }
    
}

- (void)smpcQpLoginResult:(NSNotification *)notify {
    NSLog(@"登录成功通知%@",notify);
    int error = [[[notify userInfo] objectForKey:kSmpcQuickSDKKeyError] intValue];
    NSDictionary *userInfo = [notify userInfo];
    if (error == 0) {
        NSString *uid = [[SMPCQuickSDK defaultInstance] userId];
        NSString *gameUID = [NSString stringWithFormat:@"%@@%d", uid, [SMPCQuickSDK defaultInstance].channelType];
        NSString *UserName = [[SMPCQuickSDK defaultInstance] userId];
        //获取user_token，用于从服务器去验证用户信息
        NSString *user_token = userInfo[kSmpcQuickSDKKeyUserToken];
        
        NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSDictionary dictionaryWithObjectsAndKeys:user_token, @"token",
                                UserName, @"userName",
                                gameUID, @"account", nil],@"info",
                               [NSNumber numberWithInt:S2U_FreePlatformLoginOk], @"code", nil];
        [self SendMessageToUnity:_dict];
    }
}

- (void)smpcQpLogoutResult:(NSNotification *)notify {
    NSLog(@"%s",__func__);
    NSDictionary *userInfo = notify.userInfo;
    int errorCode = [userInfo[kSmpcQuickSDKKeyError] intValue];
    switch (errorCode) {
        case SMPC_QUICK_SDK_ERROR_NONE:
        {
            NSLog(@"注销成功");
            //注销成功
            NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:S2U_FreePlatformLogoutOk], @"code", nil];
            [self SendMessageToUnity:_dict];
        }
            break;
        case SMPC_QUICK_SDK_ERROR_LOGOUT_FAIL:
        default:
        {
            //注销失败
            NSLog(@"注销失败");
        }
            break;
    }
    if (errorCode == SMPC_QUICK_SDK_ERROR_NONE) {
        
    }
    
}

- (void)smpcQpRechargeResult:(NSNotification *)notify{
    NSLog(@"充值结果%@",notify);
    NSDictionary *userInfo = notify.userInfo;
    int error = [[userInfo objectForKey:kSmpcQuickSDKKeyError] intValue];
    switch (error) {
        case SMPC_QUICK_SDK_ERROR_NONE:
        {
            //充值成功
            //QuickSDK订单号,cp下单时传入的订单号，渠道sdk的订单号，cp下单时传入的扩展参数
            NSString *orderID = userInfo[kSmpcQuickSDKKeyOrderId];
            NSString *cpOrderID = userInfo[kSmpcQuickSDKKeyCpOrderId];
            NSLog(@"充值成功数据：%@,%@",orderID,cpOrderID);
            NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [NSNumber numberWithInt:S2U_FreePlatformPayOk], @"code", nil];
            [self SendMessageToUnity:_dict];
        }
            break;
        case SMPC_QUICK_SDK_ERROR_RECHARGE_CANCELLED:
        case SMPC_QUICK_SDK_ERROR_RECHARGE_FAILED:
        {
            //充值失败
            NSString *orderID = userInfo[kSmpcQuickSDKKeyOrderId];
            NSString *cpOrderID = userInfo[kSmpcQuickSDKKeyCpOrderId];
            NSLog(@"充值失败数据%@,%@",orderID,cpOrderID);
            NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [NSNumber numberWithInt:S2U_FreePlatformPayFail], @"code", nil];
            [self SendMessageToUnity:_dict];
        }
            break;
        default:
            break;
    }
}

-(id) APNativeJSONObject:(NSData *)data{
    if (!data) {
        return nil;
    }
    
    NSError *error = nil;
    id retId = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    
    if (error) {
        NSLog(@"%s trans data to obj with error: %@", __func__, error);
        return nil;
    }
    
    return retId;
}

-(void)HandleUnityMessage:(NSString *)json {
    
    NSLog(@"收到Unity发来的消息 => %@", json);
    
    NSData *_jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *_dict = [self APNativeJSONObject:_jsonData];
    
    switch([[_dict objectForKey:@"code"] intValue]){
        case U2S_Init:
            sAppID = _dict[@"appID"];
            sGameID = _dict[@"gameID"];
            [self Init];

            break;
        case U2S_CopyContent:
            [UIPasteboard generalPasteboard].string = _dict[@"content"];
            break;
        case U2S_FreePlatformInit:
            break;
        case U2S_MakeKeyAndVisible:
        {
            UIWindow * _window = [[UIApplication sharedApplication].delegate window];
            if (_window != nil && _window.rootViewController != nil) {
                [_window makeKeyAndVisible];
            }
        }
            break;
        case U2S_OpenWebView:
            [self OpenURL:_dict[@"url"]];
            break;
        case U2S_FreePlatformLogin:
        {
            int error = [[SMPCQuickSDK defaultInstance] login];
            if (error != 0) {
                NSLog(@"U2S_FreePlatformLogin => %d",error);
            }
        }
            break;
        case U2S_FreePlatformLogout:
        {
            [[SMPCQuickSDK defaultInstance] logout];
        }
            break;
        case U2S_CreateRole:
        {
            // 更新角色信息
            SMPCQuickSDKGameRoleInfo *gameRoleInfo = [SMPCQuickSDKGameRoleInfo new];
            gameRoleInfo.serverName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"serverName"]];
            gameRoleInfo.gameRoleName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleName"]];
            gameRoleInfo.serverId = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"sid"]]; //需要是数字字符串
            gameRoleInfo.gameRoleID = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleID"]];
            gameRoleInfo.gameUserBalance = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"money"]];
            gameRoleInfo.vipLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"vipLevel"]];
            gameRoleInfo.gameUserLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"level"]];
            gameRoleInfo.partyName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"familyName"]];
            gameRoleInfo.creatTime = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"createTime"]];
            
            [[SMPCQuickSDK defaultInstance] updateRoleInfoWith:gameRoleInfo isCreate:YES];//如果这个角色是刚刚创建的，这里isCreate可以传YES
            break;
        }
        case U2S_RoleLogin:
        {
            // 更新角色信息
            SMPCQuickSDKGameRoleInfo *gameRoleInfo = [SMPCQuickSDKGameRoleInfo new];
            gameRoleInfo.serverName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"serverName"]];
            gameRoleInfo.gameRoleName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleName"]];
            gameRoleInfo.serverId = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"sid"]]; //需要是数字字符串
            gameRoleInfo.gameRoleID = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleID"]];
            gameRoleInfo.gameUserBalance = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"money"]];
            gameRoleInfo.vipLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"vipLevel"]];
            gameRoleInfo.gameUserLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"level"]];
            gameRoleInfo.partyName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"familyName"]];
            gameRoleInfo.creatTime = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"createTime"]];

            [[SMPCQuickSDK defaultInstance] updateRoleInfoWith:gameRoleInfo isCreate:NO];//如果这个角色是刚刚创建的，这里isCreate可以传YES
            break;
        }
            
        case U2S_RoleLevelUp:
        {
            // 更新角色信息
            SMPCQuickSDKGameRoleInfo *gameRoleInfo = [SMPCQuickSDKGameRoleInfo new];
            gameRoleInfo.serverName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"serverName"]];
            gameRoleInfo.gameRoleName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleName"]];
            gameRoleInfo.serverId = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"sid"]]; //需要是数字字符串
            gameRoleInfo.gameRoleID = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleID"]];
            gameRoleInfo.gameUserBalance = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"money"]];
            gameRoleInfo.vipLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"vipLevel"]];
            gameRoleInfo.gameUserLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"level"]];
            gameRoleInfo.partyName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"familyName"]];
            gameRoleInfo.creatTime = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"createTime"]];
            
            [[SMPCQuickSDK defaultInstance] updateRoleInfoWith:gameRoleInfo isCreate:NO];//如果这个角色是刚刚创建的，这里isCreate可以传YES
            break;
        }
        case U2S_FreePlatformPay:
        {
            SMPCQuickSDKGameRoleInfo *role = [[SMPCQuickSDKGameRoleInfo alloc] init];
            SMPCQuickSDKPayOrderInfo *order = [[SMPCQuickSDKPayOrderInfo alloc] init];

            role.serverName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"serverName"]];
            role.gameRoleName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleName"]];
            role.serverId = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"sid"]]; //需要是数字字符串
            role.gameRoleID = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleID"]];
            role.gameUserBalance = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"money"]];
            role.vipLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"vipLevel"]];
            role.gameUserLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"level"]];
            role.partyName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"familyName"]];
            role.creatTime = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"createTime"]];
            
            order.goodsID = [NSString stringWithFormat:@"%@", [_dict objectForKey:@"cpInfo"]]; //必填 iap时注意和苹果开发者后台一致，或者渠道映射的
            order.productName = [NSString stringWithFormat:@"%@", [_dict objectForKey:@"title"]];//必填
            order.cpOrderID = [NSString stringWithFormat:@"%@", [_dict objectForKey:@"orderId"]]; //必填 游戏订单号
            order.count = 1;  //必填 数量
            order.amount = [[_dict objectForKey:@"mount"] floatValue]; //必填 总价
            
//            NSString *_appid = [[SMPCQuickSDK defaultInstance] getConfigValue:@"zfappid"];
//            if (_appid == nil || [_appid isEqualToString:@""])
//            {
//                _appid = sAppID;
//            }
            NSString *_appid = sAppID;
            order.extrasParams = [NSString stringWithFormat:@"{\"appid\":\"%@\",\"cpinfo\":\"%@\",\"cporderid\":\"%@\"}",
                                  _appid,
                                  [_dict objectForKey:@"cpInfo"],
                                  [_dict objectForKey:@"orderId"]
                                  ];
//            //个别渠道要求单价*数量==总价
//            if([SMPCQuickSDK defaultInstance].channelType == 9999){
//                //通过判断渠道号处理特定渠道的参数
//                order.goodsID = @"productlist.name";
//            }
            int error = [[SMPCQuickSDK defaultInstance] payOrderInfo:order
                                                            roleInfo:role];
            if (error!=0)
                NSLog(@"%d", error);
        }
            break;
        case U2S_BatteryListenStart:
            if(_thread == NULL)
            {
                _thread = [[NSThread alloc] initWithTarget:self selector:@selector(BatteryThread) object:nil];
                [_thread setName:@"BatteryCheck"];
            }
            if(![_thread isExecuting])
            {
                [_thread start];
            }
            break;
        case U2S_BatteryListenStop:
            break;
    }
}
@end

extern "C" void native_opus_init(int frequency, int bitRate, int bandMode)
{
    s_frequency = frequency;
    s_bandMode = bandMode;
    s_bitRate = bitRate;
    s_frameSize = frequency / 100;
}

extern "C" int native_opus_encode(opus_int16 *pcm, int len, unsigned char *opus)
{
    int errorCode = 0;
    opus_int32 skip = 0;
    OpusEncoder *enc = opus_encoder_create(s_frequency, CHANNEL_NUM, OPUS_APPLICATION_VOIP, &errorCode);
    if (OPUS_OK != errorCode) {
        enc = NULL;
        return -1;
    }
    
    opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(s_bandMode));
    opus_encoder_ctl(enc, OPUS_SET_BITRATE(s_bitRate));
    opus_encoder_ctl(enc, OPUS_SET_VBR(1));
    opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(10));
    opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(0));
    opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(OPUS_SIGNAL_VOICE));
    opus_encoder_ctl(enc, OPUS_SET_DTX(0));
    opus_encoder_ctl(enc, OPUS_SET_PACKET_LOSS_PERC(0));
    opus_encoder_ctl(enc, OPUS_GET_LOOKAHEAD(&skip));
    opus_encoder_ctl(enc, OPUS_SET_LSB_DEPTH(16));
    
    unsigned char *rbytes = opus;
    opus_int16 *frame = pcm;
    int totalSize = 0;
    while (len >= s_frameSize)
    {
        opus_int32 length = opus_encode(enc, frame, s_frameSize, rbytes + sizeof(char), s_bitRate);
        rbytes[0] = length;
        frame += s_frameSize;
        rbytes += length + sizeof(char);
        len -= s_frameSize;
        totalSize += length;
    }
    opus_encoder_destroy(enc);
    return totalSize;
}

extern "C" int native_opus_decode(unsigned char *opus, int len, short *pcm)
{
    int err = 0;
    //opus_int32 skip = 0;
    
    OpusDecoder *dec = opus_decoder_create(s_frequency, CHANNEL_NUM, &err);
    if (err != OPUS_OK) {
        dec = NULL;
        return -1;
    }
    
    while (len > 0)
    {
        int frame_opus_length = opus[0];
        int length = opus_decode(dec, opus + sizeof(char), frame_opus_length, pcm, s_frameSize, 0);
        opus += sizeof(char) + frame_opus_length;
        pcm += s_frameSize;
        len = len - frame_opus_length - sizeof(char);
    }
    opus_decoder_destroy(dec);
    return 0;
}
