/************************************************************
 *  * Hyphenate CONFIDENTIAL
 * __________________
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of Hyphenate Inc.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Hyphenate Inc.
 */

#import <UserNotifications/UserNotifications.h>
#import "EaseSDKHelper.h"


//@interface EMChatImageOptions : NSObject<IChatImageOptions>
//
//@property (assign, nonatomic) CGFloat compressionQuality;
//
//@end

static EaseSDKHelper *helper = nil;

@implementation EaseSDKHelper

@synthesize isShowingimagePicker = _isShowingimagePicker;

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self commonInit];
    }
    
    return self;
}

+(instancetype)shareHelper
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[EaseSDKHelper alloc] init];
    });
    
    return helper;
}

#pragma mark - private

- (void)commonInit
{
    
}

#pragma mark - app delegate notifications

/** @brief 注册App切入后台和进入前台的通知 */
- (void)_setupAppDelegateNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidEnterBackgroundNotif:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
}

- (void)appDidEnterBackgroundNotif:(NSNotification*)notif
{
    [[EMClient sharedClient] applicationDidEnterBackground:notif.object];
}

- (void)appWillEnterForeground:(NSNotification*)notif
{
    [[EMClient sharedClient] applicationWillEnterForeground:notif.object];
}

#pragma mark - register apns

/** @brief 注册远程通知 */
- (void)_registerRemoteNotification
{
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber = 0;
    
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError *error) {
            if (granted) {
#if !TARGET_IPHONE_SIMULATOR
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [application registerForRemoteNotifications];
                });
#endif
            }
        }];
        return;
    }
    
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
#if !TARGET_IPHONE_SIMULATOR
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
    }else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }
#endif
}

#pragma mark - init Hyphenate

- (void)hyphenateApplication:(UIApplication *)application
                      appkey:(NSString *)appkey
                apnsCertName:(NSString *)apnsCertName
{
    [self _setupAppDelegateNotifications];
    [self _registerRemoteNotification];
    
    EMOptions *options = [EMOptions optionsWithAppkey:appkey];
    options.apnsCertName = apnsCertName;
    options.isAutoAcceptGroupInvitation = YES;
    options.enableConsoleLog = NO;
    options.usingHttpsOnly = NO;
    [[EMClient sharedClient] initializeSDKWithOptions:options];
}

- (void)hyphenateApplication:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [[EMClient sharedClient] application:application didReceiveRemoteNotification:userInfo];
}

// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [[EMClient sharedClient] bindDeviceToken:deviceToken];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - send message
+ (EMMessage *)sendTextMessage:(NSString *)text
                            to:(NSString *)toUser
                   messageType:(EMChatType)messageType
                    messageExt:(NSDictionary *)messageExt

{
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:text];
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:toUser from:from to:toUser body:body ext:messageExt];
    message.chatType = messageType;
    
    return message;
}

+ (EMMessage *)sendCmdMessage:(NSString *)action
                           to:(NSString *)to
                  messageType:(EMChatType)messageType
                   messageExt:(NSDictionary *)messageExt
                    cmdParams:(NSArray *)params
{
    EMCmdMessageBody *body = [[EMCmdMessageBody alloc] initWithAction:action];
    if (params) {
        body.params = params;
    }
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:body ext:messageExt];
    message.chatType = messageType;
    
    return message;
}

+ (EMMessage *)sendLocationMessageWithLatitude:(double)latitude
                                     longitude:(double)longitude
                                       address:(NSString *)address
                                            to:(NSString *)to
                                   messageType:(EMChatType)messageType
                                    messageExt:(NSDictionary *)messageExt
{
    EMLocationMessageBody *body = [[EMLocationMessageBody alloc] initWithLatitude:latitude longitude:longitude address:address];
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:body ext:messageExt];
    message.chatType = messageType;
    
    return message;
}

+ (EMMessage *)sendImageMessageWithImageData:(NSData *)imageData
                                          to:(NSString *)to
                                 messageType:(EMChatType)messageType
                                  messageExt:(NSDictionary *)messageExt
{
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithData:imageData displayName:@"image"];
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:body ext:messageExt];
    message.chatType = messageType;
    
    return message;
}

+ (EMMessage *)sendImageMessageWithImage:(UIImage *)image
                                      to:(NSString *)to
                             messageType:(EMChatType)messageType
                              messageExt:(NSDictionary *)messageExt
{
    NSData *data = UIImageJPEGRepresentation(image, 1);
    
    return [self sendImageMessageWithImageData:data to:to messageType:messageType messageExt:messageExt];
}

+ (EMMessage *)sendVoiceMessageWithLocalPath:(NSString *)localPath
                                    duration:(NSInteger)duration
                                          to:(NSString *)to
                                 messageType:(EMChatType)messageType
                                  messageExt:(NSDictionary *)messageExt
{
    EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc] initWithLocalPath:localPath displayName:@"audio"];
    body.duration = (int)duration;
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:body ext:messageExt];
    message.chatType = messageType;
    
    return message;
}

//点击登陆后的操作 - 登录环信
- (void)loginEaseWithUsername:(NSString *)username
                     password:(NSString *)password
{
    [[EMClient sharedClient] loginWithUsername:username password:password completion:^(NSString *aUsername, EMError *aError) {
        EMError *error =  aError;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                //设置是否自动登录
                [[EMClient sharedClient].options setIsAutoLogin:YES];
                NSLog(@"emclient login");
            } else {
                NSLog(@"emclient login error");
                switch (error.code)
                {
                    case EMErrorUserNotFound:
                        [self againRegisterAccout];
//                        NSLog(@"huanxin errorDescription ----------- %@", LanguageStr(@"MessageListVC_title1"));
                        break;
                    case EMErrorNetworkUnavailable:
//                        NSLog(@"huanxin errorDescription ----------- %@", LanguageStr(@"MessageListVC_title2"));
                        break;
                    case EMErrorServerNotReachable:
//                        NSLog(@"huanxin errorDescription ----------- %@", LanguageStr(@"MessageListVC_title3"));
                        break;
                    case EMErrorUserAuthenticationFailed:
//                        NSLog(@"huanxin errorDescription ----------- %@", error.errorDescription);
                        break;
                    case EMErrorServerTimeout:
//                        NSLog(@"huanxin errorDescription ----------- %@", LanguageStr(@"MessageListVC_title4"));
                        break;
                    case EMErrorServerServingForbidden:
//                        NSLog(@"huanxin errorDescription ----------- %@", LanguageStr(@"MessageListVC_title5"));
                        break;
                    case EMErrorUserLoginTooManyDevices:
//                        NSLog(@"huanxin errorDescription ----------- %@", LanguageStr(@"MessageListVC_title6"));
                        break;
                    case EMErrorUserNotLogin:
                        //                        NSLog(@"huanxin errorDescription ----------- %@", LanguageStr(@"MessageListVC_title6"));
                        break;
                        
                    default:
//                        NSLog(@"huanxin errorDescription ----------- %@", LanguageStr(@"MessageListVC_title7"));
                        break;
                }
            }
        });
    }];
}

- (void)againRegisterAccout{
    //==注册环信账号==//
//    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
//    [[BaseManagersFactory getHttpsManager] haya_registerEaseAccount:params callback:^(EaseModel *object, NSError *error) {//
//        if (!error) {
//            if (object.error_code==0) {
//                NSString *username = [[NSString alloc] initWithFormat:@"%d",object.id];
//                [self haya_loginEaseWithUsername:username password:object.im_password];
//            }
//        }
//    }];
}


#pragma mark - 退出环信
- (void)easeLogout {
    [[EMClient sharedClient] logout:YES completion:^(EMError *aError) {
        if (aError) {
            NSLog(@"haya_easeLogout = %@", aError.errorDescription);
        }
    }];
}

- (NSArray *)getAllConversations{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    return conversations;
}

/// 发送消息
/// @param aMessage <#aMessage description#>
/// @param aProgressBlock <#aProgressBlock description#>
/// @param aCompletionBlock <#aCompletionBlock description#>
+ (void)sendMessage:(EMMessage *)aMessage
           progress:(void (^)(int progress))aProgressBlock
         completion:(void (^)(EMMessage *message, EMError *error))aCompletionBlock{
    [[EMClient sharedClient].chatManager sendMessage:aMessage progress:aProgressBlock completion:aCompletionBlock];
}
@end