//
//  GexinPushMgr.m
//  Macalline
//
//  Created by JianjiYuan on 14-12-1.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "GexinPushMgr.h"
#import <MPNotificationView.h>
#import <AudioToolbox/AudioToolbox.h>
#import "DBDaoMgr.h"

@interface GexinPushMgr () < MPNotificationViewDelegate >

@end

@implementation GexinPushMgr

+ (GexinPushMgr *)getInstance
{
    static GexinPushMgr* instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[GexinPushMgr alloc] init];
    });
    return instance;
}

- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret
{
    if (!_gexinPusher) {
        _gexinStatus = GexinStatusStoped;
        
        self.appID = appID;
        self.appKey = appKey;
        self.appSecret = appSecret;
        
        _clientId = nil;
        
        NSError *err = nil;
        _gexinPusher = [GexinSdk createSdkWithAppId:_appID
                                             appKey:_appKey
                                          appSecret:_appSecret
                                         appVersion:@"0.0.0"
                                           delegate:self
                                              error:&err];
        if (!_gexinPusher) {
            //            [_viewController logMsg:[NSString stringWithFormat:@"%@", [err localizedDescription]]];
        } else {
            _gexinStatus = GexinStatusStarted;
        }
        
        //        [_viewController updateStatusView:self];
    }
}

- (void)stopSdk
{
    if (_gexinPusher) {
        [_gexinPusher destroy];
        _gexinPusher = nil;
        _gexinStatus = GexinStatusStoped;
        
        _clientId = nil;
        
        //        [_viewController updateStatusView:self];
    }
}

- (BOOL)checkSdkInstance
{
    if (!_gexinPusher) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误" message:@"SDK未启动" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        return NO;
    }
    return YES;
}

- (void)setDeviceToken:(NSString *)aToken
{
    if (![self checkSdkInstance]) {
        return;
    }
    
    [_gexinPusher registerDeviceToken:aToken];
}

- (BOOL)setTags:(NSArray *)aTags error:(NSError **)error
{
    if (![self checkSdkInstance]) {
        return NO;
    }
    
    return [_gexinPusher setTags:aTags];
}

- (NSString *)sendMessage:(NSData *)body error:(NSError **)error {
    if (![self checkSdkInstance]) {
        return nil;
    }
    
    return [_gexinPusher sendMessage:body error:error];
}

#pragma mark - GexinSdkDelegate
- (void)GexinSdkDidRegisterClient:(NSString *)clientId
{
    // [4-EXT-1]: 个推SDK已注册
    _gexinStatus = GexinStatusStarted;
    self.clientId = clientId;
    //    [_viewController updateStatusView:self];
    DLog(@"[GexinPushMgr getInstance].clientId %@", [GexinPushMgr getInstance].clientId?:@"");
    
    if (clientId && ![clientId isEqualToString:@""]) {
        [UIApplication saveObject:clientId type:String key:kClientIdOfApplication];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"shouldBlendClientId" object:nil];
    }
    
    //    [self stopSdk];
}

- (void)GexinSdkDidReceivePayload:(NSString *)payloadId fromApplication:(NSString *)appId
{
    // [4]: 收到个推消息
    self.payloadId = payloadId;
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    NSData *payload = [_gexinPusher retrivePayloadById:payloadId];
    NSString *payloadMsg = nil;
    if (payload) {
        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
                                              length:payload.length
                                            encoding:NSUTF8StringEncoding];
    }
    
    NSString *record = [NSString stringWithFormat:@"%d, %@, %@", ++_lastPayloadIndex, [NSDate date], payloadMsg];
    
    DLog(@"GexinSdkDidReceivePayload  %@", record);
    
    DLog(@"payloadMsg %@ \nkLocalNotifyRecievedContent %@", payloadMsg, [UIApplication getObjectType:String key:kLocalNotifyRecievedContent]);
    
    if ([payloadMsg isEqualToString:[UIApplication getObjectType:String key:kAPNFetchPayloadMsg]]) {
        [UIApplication saveObject:@"" type:String key:kAPNFetchPayloadMsg];
        return;
    }
    
    NSDictionary *dictPayload = [NSJSONSerialization JSONObjectWithData:[payloadMsg dataUsingEncoding:NSUTF8StringEncoding]
                                                                options:NSJSONReadingAllowFragments
                                                                  error:nil];
    if (!dictPayload ||
        ![dictPayload isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    if (![dictPayload[@"type"] isEqualToString:@"16002"]) {
        [DBDaoMgr insertNotice:dictPayload];
    }
    
    UIImage *image = [UIImage imageNamed:@"80.png"];
    MPNotificationView *notificationView = [MPNotificationView notifyWithText:dictPayload[@"title"]
                                                                       detail:dictPayload[@"content"]
                                                                        image:image
                                                                  andDuration:10];
    notificationView.delegate = self;
//    notificationView.userInfo = dictPayload;
    
    NSString* str = [NSString stringWithFormat:@"%@",dictPayload[@"type"]];
    if (![str isEqualToString:@"16002"]) {
        [DBDaoMgr insertNotice:dictPayload];
    }
    
    if ([[UIApplication getObjectType:String key:kLocalNotifyShakeEnable] boolValue]) {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
    if ([[UIApplication getObjectType:String key:kLocalNotifySoundEnable] boolValue]) {
        SystemSoundID sound;//系统声音的id 取值范围为：1000-2000
        NSString *path = [NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@.%@",@"sms-received1",@"caf"];
        //[[NSBundle bundleWithIdentifier:@"com.apple.UIKit" ]pathForResource:soundName ofType:soundType];//得到苹果框架资源UIKit.framework ，从中取出所要播放的系统声音的路径
        //[[NSBundle mainBundle] URLForResource: @"tap" withExtension: @"aif"];  获取自定义的声音
        if (path) {
            OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&sound);
            if (error != kAudioServicesNoError) {//获取的声音的时候，出现错误
                
            }
        }
        AudioServicesPlaySystemSound(sound);
    }
    
    [UIApplication saveObject:payloadMsg type:String key:kLocalNotifyRecievedContent];
    [[NSNotificationCenter defaultCenter] postNotificationName:kGexinPushMgrPayloadRecieved object:dictPayload];
    
}

- (void)GexinSdkDidSendMessage:(NSString *)messageId result:(int)result
{
    // [4-EXT]:发送上行消息结果反馈
    NSString *record = [NSString stringWithFormat:@"Received sendmessage:%@ result:%d", messageId, result];
    //    [_viewController logMsg:record];
    DLog(@"GexinSdkDidSendMessage  %@", record);
}

- (void)GexinSdkDidOccurError:(NSError *)error
{
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    //    [_viewController logMsg:[NSString stringWithFormat:@">>>[GexinSdk error]:%@", [error localizedDescription]]];
    DLog(@"GexinSdkDidOccurError  %@", [NSString stringWithFormat:@">>>[GexinSdk error]:%@", [error localizedDescription]]);
}

- (void)applicationDidBecomeActive
{
    [self startSdkWith:kAppId appKey:kAppKey appSecret:kAppSecret];
}

- (void)applicationDidEnterBackground
{
    [self stopSdk];
}

//Method To deal
- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    _deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    DLog(@"didRegisterForRemoteNotificationsWithDeviceToken:%@", _deviceToken);
    // [3]:向个推服务器注册deviceToken
    if (_gexinPusher) {
        [_gexinPusher registerDeviceToken:_deviceToken];
    }
}

- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    // [3-EXT]:如果APNS注册失败，通知个推服务器
    if (_gexinPusher) {
        [_gexinPusher registerDeviceToken:@""];
    }
    DLog(@"didFailToRegisterForRemoteNotificationsWithError  %@", [error localizedDescription]);
    //	[_viewController logMsg:[NSString stringWithFormat:@"didFailToRegisterForRemoteNotificationsWithError:%@", [error localizedDescription]]];
}

- (void)didReceiveRemoteNotification:(NSDictionary *)userinfo
{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    // [4-EXT]:处理APN
    NSString *payloadMsg = [userinfo objectForKey:@"payload"];
    NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], payloadMsg];
    //    [_viewController logMsg:record];
    DLog(@"didReceiveRemoteNotification  %@", record);
    
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        
        NSDictionary *dictPayload = [NSJSONSerialization JSONObjectWithData:[payloadMsg dataUsingEncoding:NSUTF8StringEncoding]
                                                                    options:NSJSONReadingAllowFragments
                                                                      error:nil];
        [UIApplication saveObject:payloadMsg type:String key:kLocalNotifyRecievedContent];
        [[NSNotificationCenter defaultCenter] postNotificationName:kGexinPushMgrPayloadRecieved object:dictPayload];
//        [DataMgr getInstance].remoteNotificationID = dictPayload[@"id"];
    }
}

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    // [4-EXT]:处理APN
    NSString *payloadMsg = [userInfo objectForKey:@"payload"];
    
    NSDictionary *aps = [userInfo objectForKey:@"aps"];
    NSNumber *contentAvailable = aps == nil ? nil : [aps objectForKeyedSubscript:@"content-available"];
    
    NSString *record = [NSString stringWithFormat:@"[APN]%@, %@, [content-available: %@]", [NSDate date], payloadMsg, contentAvailable];
    //    [_viewController logMsg:record];
    DLog(@"didReceiveRemoteNotification  fetchCompletionHandler  %@", record);
    
    NSDictionary *dictPayload = [NSJSONSerialization JSONObjectWithData:[payloadMsg dataUsingEncoding:NSUTF8StringEncoding]
                                                                options:NSJSONReadingAllowFragments
                                                                  error:nil];
    if (!dictPayload ||
        ![dictPayload isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
//    [DataMgr getInstance].remoteNotificationID = dictPayload[@"id"];
    
    //    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
    //
    //        UIImage *image = [UIImage imageNamed:@"80.png"];
    //        MPNotificationView *notificationView = [MPNotificationView notifyWithText:dictPayload[@"title"]
    //                                                                           detail:dictPayload[@"content"]
    //                                                                            image:image
    //                                                                      andDuration:10];
    //        notificationView.delegate = self;
    //        notificationView.userInfo = dictPayload;
    //
    //        if ([[UIApplication getObjectType:String key:kLocalNotifyShakeEnable] boolValue]) {
    //            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    //        }
    //        if ([[UIApplication getObjectType:String key:kLocalNotifySoundEnable] boolValue]) {
    //            SystemSoundID sound;//系统声音的id 取值范围为：1000-2000
    //            NSString *path = [NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@.%@",@"sms-received1",@"caf"];
    //            //[[NSBundle bundleWithIdentifier:@"com.apple.UIKit" ]pathForResource:soundName ofType:soundType];//得到苹果框架资源UIKit.framework ，从中取出所要播放的系统声音的路径
    //            //[[NSBundle mainBundle] URLForResource: @"tap" withExtension: @"aif"];  获取自定义的声音
    //            if (path) {
    //                OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&sound);
    //                if (error != kAudioServicesNoError) {//获取的声音的时候，出现错误
    //
    //                }
    //            }
    //            AudioServicesPlaySystemSound(sound);
    //        }
    //
    //    }
    
    [UIApplication saveObject:payloadMsg type:String key:kAPNFetchPayloadMsg];
    
    //    [UIApplication saveObject:payloadMsg type:String key:kLocalNotifyRecievedContent];
    //    [[NSNotificationCenter defaultCenter] postNotificationName:kGexinPushMgrPayloadRecieved object:dictPayload];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)registerRemoteNotification
{
#ifdef __IPHONE_8_0
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        
        UIUserNotificationSettings *uns = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:uns];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
#else
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
#endif
}

- (void)unRegisterRemoteNotification
{
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];
}

- (void)didTapOnNotificationView:(MPNotificationView *)notificationView
{
    if (_delegate &&
        [_delegate respondsToSelector:@selector(didTapOnNotificationWithPayload:)]) {
//        [_delegate didTapOnNotificationWithPayload:notificationView.userInfo];
    }
}

- (void)setupLocalNotification
{
    UILocalNotification *notification=[[UILocalNotification alloc] init];
    if (notification!=nil) {
        NSDate *now=[NSDate new];
        notification.fireDate=[now dateByAddingTimeInterval:10];//10秒后通知
        notification.repeatInterval=0;//循环次数，kCFCalendarUnitWeekday一周一次
        notification.timeZone=[NSTimeZone defaultTimeZone];
        notification.applicationIconBadgeNumber=1; //应用的红色数字
        notification.soundName= UILocalNotificationDefaultSoundName;//声音，可以换成alarm.soundName = @"myMusic.caf"
        //去掉下面2行就不会弹出提示框
        notification.alertBody=@"通知内容";//提示信息 弹出提示框
        notification.alertAction = @"打开";  //提示框按钮
        //notification.hasAction = NO; //是否显示额外的按钮，为no时alertAction消失
        
        // NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
        //notification.userInfo = infoDict; //添加额外的信息
        
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        
    }
    
}

@end
