//
//  AppDelegate.m
//  FunCellPackDemo
//
//  Created by 胡鑫 on 16/6/1.
//  Copyright © 2016年 huxin. All rights reserved.
//

#import "AppDelegate.h"
#include "PlatformInterface.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

#pragma mark 系统周期

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.viewController = [[[ViewController alloc] init] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    
    NSLog(@"packdemo didFinishLaunchingWithOptions");
    [FunCellPlatform sharedInstance].funcellplatformdelegate = self;
    [[FunCellPlatform sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    return [[FunCellPlatform sharedInstance] applicationWillResignActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[FunCellPlatform sharedInstance] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    [[FunCellPlatform sharedInstance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    NSLog(@"packdemo applicationDidBecomeActive 0");
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[FunCellPlatform sharedInstance] applicationDidBecomeActive:application];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[FunCellPlatform sharedInstance] applicationWillTerminate:application];
}

#ifdef __IPHONE_9_0
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    NSLog(@"packdemo openURL options 0");
    return [[FunCellPlatform sharedInstance] application:application openURL:url options:options];
}
#endif

//Deprecated in iOS 9.0.
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    NSLog(@"packdemo openURL sourceApplication 0");
    return [[FunCellPlatform sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
     NSLog(@"packdemo handleOpenURL 0");
    return [[FunCellPlatform sharedInstance] application:application handleOpenURL:url];
}

-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return [[FunCellPlatform sharedInstance] application:application supportedInterfaceOrientationsForWindow:window];
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [[FunCellPlatform sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    [[FunCellPlatform sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
}

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [[FunCellPlatform sharedInstance] application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

//Local Push Handler
- (void)application:(UIApplication*)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    [[FunCellPlatform sharedInstance] application:application didReceiveLocalNotification:notification];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    [[FunCellPlatform sharedInstance] applicationDidReceiveMemoryWarning:application];
}

#pragma mark sdk回调

/**
 *sdk初始化成功回调
 */
- (void)FCPDInitSuccessCallback
{
    NSLog(@"AppDelegate FCPDInitSuccessCallback");
    
    CPlatformInterface::initSdkCallback();
}

/**
 *登录成功回调
 */
- (void)FCPDLoginCallBack:(NSString *)username anduserid:(NSString *)userID andsessionid:(NSString *)sessionID andtoken:(NSString *)token anddatadict:(NSDictionary *)datadict
{
    NSLog(@"AppDelegate FCPDLoginCallBack username:%@, userID:%@, sessionID:%@, token:%@, datadict:%@", username, userID, sessionID, token, datadict);
    NSData* data = [NSJSONSerialization dataWithJSONObject:datadict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* jsonstr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSString* nsdatadict = [NSString stringWithString:jsonstr];
    [jsonstr release];
    jsonstr = nil;
    
    CPlatformInterface::LoginSuccess([username UTF8String], [userID UTF8String], [sessionID UTF8String], [token UTF8String], [nsdatadict UTF8String]);
    
    //just demo code
    [[ViewController shareInstace] doLoginSuccess];
}

/**
 *切换账号回调
 */
- (void)FCPDSwichAccountCallBack:(NSString *)username anduserid:(NSString *)userID andsessionid:(NSString *)sessionID andtoken:(NSString *)token anddatadict:(NSDictionary *)datadict
{
    NSLog(@"AppDelegate FCPDSwichAccountCallBack username:%@, userID:%@, sessionID:%@, token:%@, datadict:%@", username, userID, sessionID, token, datadict);
    
    NSData* data = [NSJSONSerialization dataWithJSONObject:datadict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* jsonstr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSString* nsdatadict = [NSString stringWithString:jsonstr];
    [jsonstr release];
    jsonstr = nil;
    
    CPlatformInterface::SwichAccount([username UTF8String], [userID UTF8String], [sessionID UTF8String], [token UTF8String], [nsdatadict UTF8String]);
}

/**
 *登陆失败回调
 */
- (void)FCPDLoginFailOrClose:(NSString*)result
{
    NSLog(@"AppDelegate FCPDLoginFailOrClose result:%@", result);
    //result值,失败时为@"fail",取消时为@"close"
    if ( [result isEqualToString:@"fail"] )
    {
        //登陆失败
        CPlatformInterface::LoginCancel(0);
    }else if ( [result isEqualToString:@"close"] )
    {
        //取消登陆
        CPlatformInterface::LoginCancel(1);
    }else
    {
        //异常了
        CPlatformInterface::LoginCancel(0);
    }
}

/**
 *注册或游客登录成功回调
 */
- (void)FCPDRegisterCloseCallback
{
    NSLog(@"AppDelegate FCPDRegisterCloseCallback");
    CPlatformInterface::RegisterCloseCallback();
}

/**
 *funcell订单查询回调,接入服务器通知订单完成的不用管
 */
- (void)FCPDPayCallBack:(NSString *)billNo andaccesstoken:(NSString *)accessToken
{
    NSLog(@"AppDelegate FCPDPayCallBack billNo:%@, token:%@", billNo, accessToken);
    CPlatformInterface::payCallback([billNo UTF8String], [accessToken UTF8String]);
}

/**
 *渠道支付成功回调
 *billNo
 平台订单号
 *extData
 调用支付传入的附加字符串,透传参数
 */
- (void)FCPDPaySuccessCallBack:(NSString*)billNo andextdata:(NSString *)extData
{
    NSLog(@"AppDelegate FCPDPaySuccessCallBack billNo:%@, extData:%@", billNo, extData);
    CPlatformInterface::PaySuccessCallBack([billNo UTF8String], [extData UTF8String]);
}

/**
 *渠道支付失败回调
 *information
 回调通知信息
 */
- (void)FCPDPayFailCallBack:(NSString*)information
{
    NSLog(@"AppDelegate FCPDPayFailCallBack information:%@", information);
    CPlatformInterface::PayFailCallBack([information UTF8String]);
}

/**
 *渠道支付取消回调
 *information
 回调通知信息
 */
- (void)FCPDPayCancelCallBack:(NSString*)information
{
    NSLog(@"AppDelegate FCPDPayCancelCallBack information:%@", information);
    CPlatformInterface::PayCancelCallBack([information UTF8String]);
}

/**
 *渠道回调支付关闭界面,网络请求失败,未知错误等
 *information
 回调通知信息
 */
- (void)FCPDPayClosePayPage:(NSString*)information
{
    NSLog(@"AppDelegate FCPDPayClosePayPage information:%@", information);
    CPlatformInterface::PayClosePayPage([information UTF8String]);
}

/**
 *sdk通知游戏退出登录
 */
- (void)FCPDPlatformToGameLogout
{
    NSLog(@"AppDelegate FCPDPlatformToGameLogout FCPDPlatformToGameLogout");
    
    CPlatformInterface::PlatformToGameLogout();
    
    //just demo code
    [[ViewController shareInstace] LogOff];
}

/**
 *获取充值列表
 */
- (void)FCPDGetPayListCallback:(NSString*)paylistresult
{
    NSLog(@"AppDelegate FCPDGetPayListCallback paylistresult:%@", paylistresult);
    
    CPlatformInterface::getPayListCallback([paylistresult UTF8String]);
    
    //just demo code
    [[ViewController shareInstace] setPayList:paylistresult];
    const char* chpaylist = [paylistresult UTF8String];
    [[ViewController shareInstace] showPayView:chpaylist];
}

/**
 *获取服务器列表回调
 */
- (void)FCPDGetServerListCallback:(NSString*)serverlist
{
    NSLog(@"AppDelegate FCPDGetServerListCallback serverlist:%@", serverlist);
    CPlatformInterface::getServerListCallback([serverlist UTF8String]);
}

/**
 *获取公告列表回调
 */
- (void)FCPDGetNoticeListCallback:(NSString*)noticelist
{
    NSLog(@"AppDelegate FCPDGetNoticeListCallback noticelist:%@", noticelist);
    CPlatformInterface::getNoticeListCallback([noticelist UTF8String]);
}

/**
 *游戏中心关闭回调,某些渠道会调
 */
- (void)FCPDGameCenterCloseCallback
{
    NSLog(@"AppDelegate FCPDGameCenterCloseCallback");
    CPlatformInterface::GameCenterCloseCallback();
}

/**
 *分享结果反馈
 *sharetype
 传入的分享类型
 *state
 分享状态,成功:@"success"，失败:@"fail"，取消:@"cancel"
 *result
 分享返回的内容
 */
- (void)FCPDShareResult:(NSString*)sharetype andState:(NSString*)state andresult:(NSDictionary*)result
{
    NSLog(@"AppDelegate FCPDShareResult sharetype:%@, state:%@, result:%@", sharetype, state, result);
    
    NSData* data = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
    NSString* jsonstr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSString* nsdatadict = [NSString stringWithString:jsonstr];
    [jsonstr release];
    jsonstr = nil;
    
    CPlatformInterface::ShareResult([sharetype UTF8String], [state UTF8String], [nsdatadict UTF8String]);
}

@end
