//
//  AppDelegate+handleSchemeURL.m
//  Gengmei
//
//  Created by wangyang on 2016/11/8.
//  Copyright © 2016年 更美互动信息科技有限公司. All rights reserved.
//

#import "AppDelegate+handleSchemeURL.h"
#import "UIViewController+UrlScheme.h"
#import <objc/runtime.h>
//#import "AppDelegate+Pay.h"
#import "AppDelegate+handleSchemeURL.h"
#import "WXApi.h"
#import "GMNotificationName.h"
#import "GMThirdPartyOauthManager.h"

@import GMCache;
@interface AppDelegate ()
@end
@implementation AppDelegate (handleSchemeURL)
/*
- (void)setDelayedSchemeURL:(NSString *)delayedSchemeURL {
    // 如果有多次调用setDelayedSchemeURL，此时只处理第一个;
    // 清空delayedSchemeURL要保证正确执行
    id oldValue = objc_getAssociatedObject(self, @selector(delayedSchemeURL));
    if (delayedSchemeURL == nil || oldValue == nil) {
        objc_setAssociatedObject(self, @selector(delayedSchemeURL), delayedSchemeURL, OBJC_ASSOCIATION_COPY);
    }
}
- (NSString *)delayedSchemeURL {
    return objc_getAssociatedObject(self, @selector(delayedSchemeURL));
}
*/
#pragma mark - Handle openURL
// iOS 8 会走这个
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [self commmonHandleOpenURL:url sourceApplication:sourceApplication];
}

// iOS 9 会走这个
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    return [self commmonHandleOpenURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]];
}

- (BOOL)commmonHandleOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication {
    /*
     在处理url时不能只判断scheme，比如下面的支付宝支付回调的url scheme就与更美协议的url scheme相同，所以采取判断host的方式
     */

    /*
    // 处理支付情况
    NSString *host = url.host;
    if ([host isEqualToString:@"safepay"]){
        // gengmei://safepay/xxxxxxx
        [self alipayCallbackWithUrl:url];
    } else if ([host isEqualToString:@"pay"]) {
        // wx4326da3ad2429149://pay/xxxxxxxx
        [self weixinPayHandleOpenURL:url];
    }*/

    // 处理更美短信协议 gengmei://launch?protocol=，当时这么判断的原因是什么？是希望判断为从短信跳转过来的吗？？？
    
    NSString *string = url.absoluteString;
    /*
    if ([string rangeOfString:SMS_OPEN_URL].length > 1) {
        self.delayedSchemeURL = [url.absoluteString substringFromIndex:SMS_OPEN_URL.length];
        [self handleDelayedSchemeURL];
    }
    // 处理从浏览器过来的更美协议
    else if ([string hasPrefix:URL_SCHEME_PREFIX] && ![sourceApplication isEqualToString:@"com.wanmeizhensuo.ZhengXing"]) {
        self.delayedSchemeURL = url.absoluteString;
        [self handleDelayedSchemeURL];
    }
    */
    // 处理从浏览器过来的更美协议
    if ([string hasPrefix:URL_SCHEME_PREFIX] && ![sourceApplication isEqualToString:@"com.wanmeizhensuo.ZhengXing"]) {
        self.delayedSchemeURL = url.absoluteString;
        [self handleDelayedSchemeURL];
    }
    if ([string hasPrefix:[NSString stringWithFormat:@"wb%@",SINAWEIBO_APPID]]) {
        return [WeiboSDK handleOpenURL:url delegate:[GMThirdPartyOauthManager shareInstance]];
    } else if([string hasPrefix:[NSString stringWithFormat:@"tencent%@",QQ_APPID]]) {
        return [TencentOAuth HandleOpenURL:url];
    } else if([string hasPrefix:[NSString stringWithFormat:@"QQ%@",QQ_HEX_APPID]]){
        NSDictionary* params = [string urlQueryToDictionary];
        NSInteger error = [params[@"error"] integerValue];
        if (error == 0) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kQQShare object:nil userInfo:@{@"state": @(GMShareResponseStateSuccess)}];
        } else if (error == -4){
            [[NSNotificationCenter defaultCenter] postNotificationName:kQQShare object:nil userInfo:@{@"state": @(GMShareResponseStateCancel)}];
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:kQQShare object:nil userInfo:@{@"state": @(GMShareResponseStateFail)}];
        }
        return [TencentOAuth HandleOpenURL:url];

    }else{
        return [WXApi handleOpenURL:url delegate:[GMThirdPartyOauthManager shareInstance]];
    }
    return YES;
}

/*
#pragma mark - UniversalLinks
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *))restorationHandler
{
    if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
        NSURL *url = userActivity.webpageURL;
        if ([url.host rangeOfString:@"igengmei.com"].length == 0) {
            return NO;
        }

        NSString *scheme = [AppDelegate schemeFromUniversalLink:url];
        if ([scheme isNonEmpty]) {
            self.delayedSchemeURL = scheme;
            [self handleDelayedSchemeURL];
        }

    }
    return YES;
}

+ (NSString *)schemeFromUniversalLink:(NSURL *)link {
    // applinks:zd.igengmei.com
    NSString *schemeURL = @"";
    if ([link.path hasPrefix:@"/promotion"]) {
        // 这是一个美购详情页, Path: /promotion/431，431为美购id
        schemeURL = [NSString stringWithFormat:@"%@%@?service_id=%@", URL_SCHEME_PREFIX, HOST_SERVICE_DETAIL, link.lastPathComponent];
    } else if ([link.path hasPrefix:@"/diary_book"]) {
        //日记本详情页 /diary_book/xxxx
        schemeURL = [NSString stringWithFormat:@"%@%@?diary_id=%@", URL_SCHEME_PREFIX, HOST_DIARY_DETAIL, link.lastPathComponent];
    } else if ([link.path hasPrefix:@"/topic"]) {
        // 帖子详情页
        schemeURL = [NSString stringWithFormat:@"%@%@?topic_id=%@", URL_SCHEME_PREFIX, HOST_TOPIC_DETAIL, link.lastPathComponent];
    } else if ([link.path hasPrefix:@"/zone"]) {
        // 圈子详情页
        schemeURL = [NSString stringWithFormat:@"%@%@?tag_id=%@&tab_type=0", URL_SCHEME_PREFIX, HOST_ZONE_DETAIL, link.lastPathComponent];
    } else if ([link.path hasPrefix:@"/user"] && [link.path hasSuffix:@"profile"]) {
        // /user/profile h5个人主页
        if (link.pathComponents.count > 3) {
            schemeURL = [NSString stringWithFormat:@"%@%@?uid=%@", URL_SCHEME_PREFIX, HOST_HOMEPAGE, link.pathComponents[2]];
        }
    }

    return schemeURL;
}
*/

#pragma mark - Safe handle schemeURL
- (void)handleDelayedSchemeURL {
    if ([self.delayedSchemeURL isNonEmpty]) {
        [AppDelegate.visibleController pushScheme:self.delayedSchemeURL];
        self.delayedSchemeURL = nil;
    }
}
@end
