//
//  ApplozicChatManger.m
//  ApplozicSample
//
//  Created by Adarsh on 17/01/18.
//  Copyright © 2018 Facebook. All rights reserved.
//

#import "ApplozicChat.h"
#import "ALChatManager.h"
@import Applozic;

@implementation ApplozicChat

// To export a module named CalendarManager
RCT_EXPORT_MODULE();


/**
 * Login method of the user
 *
 */

RCT_EXPORT_METHOD(login:(NSDictionary *)userDetails andCallback:(RCTResponseSenderBlock)callback) {

  ALUser *aluser = [[ALUser alloc] initWithJSONString:[self getJsonString:userDetails]];

  ALChatManager *chatManger = [[ALChatManager alloc] init];

  [ALUserDefaultsHandler setUserAuthenticationTypeId:aluser.authenticationTypeId];

  [chatManger connectUserWithCompletion:aluser
                            withHandler:^(ALRegistrationResponse *rResponse, NSError *error) {

    if (error) {
      NSString *errorResponse = error.description;
      if (rResponse) {
        errorResponse = [self getJsonString:[rResponse dictionary]];
      }
      return callback(@[errorResponse, [NSNull null]]);
    } else if (rResponse.isRegisteredSuccessfully) {
      return callback(@[[NSNull null],[self getJsonString:[rResponse dictionary]]]);
    }
  }];
}

//===================================== initiating chats=================================================

/**
 * Open chats
 *
 **/
RCT_EXPORT_METHOD(openChat) {

  ALChatManager *chatManger = [[ALChatManager alloc] init];
  ALPushAssist *pushAssistant = [[ALPushAssist alloc] init];
  dispatch_async(dispatch_get_main_queue(), ^{
    [chatManger launchChat:pushAssistant.topViewController];

  });
}
/**
 * Open chat with Users
 *
 **/
RCT_EXPORT_METHOD(openChatWithUser:(NSString *)userId) {

  ALChatManager *chatManger = [[ALChatManager alloc] init];
  ALChatLauncher *chatLauncher = [[ALChatLauncher alloc] initWithApplicationId:chatManger.getApplicationKey];
  ALPushAssist* pushAssistant = [[ALPushAssist alloc] init];

  dispatch_async(dispatch_get_main_queue(), ^{

    [chatLauncher launchIndividualChat:userId withGroupId:nil andViewControllerObject:pushAssistant.topViewController andWithText:nil ];

  });

}
/**
 * Open chat with Group
 *
 **/
RCT_EXPORT_METHOD(openChatWithGroup:(nonnull NSNumber *)groupId
                  andCallback:(RCTResponseSenderBlock)callback) {

  ALChatManager *chatManger = [[ALChatManager alloc] init];
  ALChatLauncher *chatLauncher = [[ALChatLauncher alloc] initWithApplicationId:chatManger.getApplicationKey];
  ALPushAssist *pushAssistant = [[ALPushAssist alloc] init];
  ALChannelService *service = [ALChannelService new];

  [service getChannelInformationByResponse:groupId orClientChannelKey:nil withCompletion:^(NSError *error, ALChannel *channel, ALChannelFeedResponse *channelResponse) {

    if (channel) {
      dispatch_async(dispatch_get_main_queue(), ^{
        [chatLauncher launchIndividualChat:nil withGroupId:channel.key andViewControllerObject:pushAssistant.topViewController andWithText:nil];
      });
      return callback(@[[NSNull null],@"success"]);
    } else {
      return callback(@[@"channel not found", [NSNull null] ]);
    }
  }];
}

/**
 * Open chat with ClientGroupId
 *
 **/
RCT_EXPORT_METHOD(openChatWithClientGroupId:(nonnull NSString *)clientGroupId
                  andCallback:(RCTResponseSenderBlock)callback) {

  ALChatManager *chatManger = [[ALChatManager alloc] init];
  ALPushAssist *pushAssistant = [[ALPushAssist alloc] init];

  dispatch_async(dispatch_get_main_queue(), ^{

    ALChannelService *service = [ALChannelService new];
    ALChatLauncher *chatLauncher = [[ALChatLauncher alloc] initWithApplicationId:chatManger.getApplicationKey];

    [service getChannelInformationByResponse:nil orClientChannelKey:clientGroupId withCompletion:^(NSError *error, ALChannel *channel, ALChannelFeedResponse *channelResponse) {

      if (channel) {
        [chatLauncher launchIndividualChat:nil
                               withGroupId:channel.key
                   andViewControllerObject:pushAssistant.topViewController
                               andWithText:nil];
        return callback(@[[NSNull null], @"success"]);
      } else {
        return callback(@[@"channel not found", [NSNull null] ]);
      }
    }];
  });
}

//========================= Group Methods ================================================================

RCT_EXPORT_METHOD(createGroup:(NSDictionary *)channelDetails andCallback:(RCTResponseSenderBlock)callback) {

  NSString *channelName = [channelDetails valueForKey:@"groupName"];
  NSString *clientChannelKey = [channelDetails valueForKey:@"clientGroupId"];
  NSString *imageLink = [channelDetails valueForKey:@"imageUrl"];
  NSMutableArray * groupMemberList= [channelDetails objectForKey:@"groupMemberList"];
  NSMutableDictionary * groupMetaData= [channelDetails objectForKey:@"metadata"];
  NSNumber *parentChannelKey= [channelDetails objectForKey:@"parentChannelKey"];
  NSString *adminUserId= [channelDetails objectForKey:@"adminUserId"];

  ALChannelService *channelService = [[ALChannelService alloc] init];

  ALChannelInfo *channelInfo = [[ALChannelInfo alloc] init];
  channelInfo.groupName = channelName;
  channelInfo.parentKey = parentChannelKey;
  channelInfo.clientGroupId = clientChannelKey;
  channelInfo.imageUrl = imageLink;
  channelInfo.type = (short)PUBLIC;
  channelInfo.metadata = groupMetaData;
  channelInfo.admin = adminUserId;
  channelInfo.groupMemberList = groupMemberList;

  [channelService createChannelWithChannelInfo:channelInfo
                                withCompletion:^(ALChannelCreateResponse *response, NSError *error) {

    if (!error && response.alChannel) {
      response.alChannel.adminKey = [ALUserDefaultsHandler getUserId];
      ALChannelService *channelDBService = [[ALChannelService alloc] init];
      [channelDBService createChannelEntry:response.alChannel fromMessageList:NO];
      return callback(@[[NSNull null],response.alChannel.key]);
    } else if (response) {
      return callback(@[[NSNull null],[self getJsonString:response.response]]);
    } else {
      NSLog(@"ERROR_IN_CHANNEL_CREATING :: %@",error);
      return callback(@[error.description,[NSNull null]]);
    }
  }];

}

RCT_EXPORT_METHOD(addMemberToGroup:(NSDictionary *)requestData
                  andCallback:(RCTResponseSenderBlock)callback) {

  ALChannelService *alChannelService = [ALChannelService new];

  NSNumber *groupId = [requestData valueForKey:@"groupId"];
  NSString *clientGroupId = [requestData valueForKey:@"clientGroupId"];
  NSString *userId = [requestData valueForKey:@"userId"];

  [alChannelService addMemberToChannel:userId
                         andChannelKey:groupId
                    orClientChannelKey:clientGroupId
                        withCompletion:^(NSError *error, ALAPIResponse *response) {
    if (error) {
      NSLog(@"error description %@", error.description);
      return callback(@[error.description ,[NSNull null]]);
    } else if ([response.status isEqualToString:AL_RESPONSE_SUCCESS]) {
      return callback(@[[NSNull null],[self getJsonString:response.actualresponse]]);
    } else {
      return callback(@[ [self getJsonString:response.actualresponse], [NSNull null]]);
    }
  }];

}

RCT_EXPORT_METHOD(removeUserFromGroup:(NSDictionary *)requestData
                  andCallback:(RCTResponseSenderBlock)callback) {

  ALChannelService *alChannelService = [ALChannelService new];

  NSNumber *groupId = [requestData valueForKey:@"groupId"];
  NSString *clientGroupId = [requestData valueForKey:@"clientGroupId"];
  NSString *userId = [requestData valueForKey:@"userId"];

  [alChannelService removeMemberFromChannel:userId
                              andChannelKey:groupId
                         orClientChannelKey:clientGroupId
                             withCompletion:^(NSError *error, ALAPIResponse *response) {

    if (error) {
      NSLog(@"error description %@", error.description);
      return callback(@[ error.description ,[NSNull null]]);
    } else {
      return callback(@[ [NSNull null],[self getJsonString:response.dictionary]]);
    }
  }];

}

//======================================Unreadcounts ==============================================


RCT_EXPORT_METHOD(getUnreadCountForUser:(NSString*)userId
                  andCallback:(RCTResponseSenderBlock)callback) {

  ALContactService* contactService = [ALContactService new];
  ALContact *contact = [contactService loadContactByKey:@"userId" value:userId];
  NSNumber *unreadCount = [contact unreadCount];
  if (unreadCount != nil) {
    return callback(@[[NSNull null], unreadCount]);
  } else {
    return callback(@[@"Error", [NSNull null]]);
  }
}

RCT_EXPORT_METHOD(getUnreadCountForChannel:(NSDictionary *)requestData
                  andCallback:(RCTResponseSenderBlock)callback) {

  ALChannelService *channelService = [ALChannelService new];
  NSNumber *groupId = [requestData valueForKey:@"groupId"];
  NSString *clientGroupId = [requestData valueForKey:@"clientGroupId"];

  if (clientGroupId) {
    [channelService getChannelInformationByResponse:nil orClientChannelKey:clientGroupId withCompletion:^(NSError *error, ALChannel *channel, ALChannelFeedResponse *channelResponse) {

      if (channel) {
        NSNumber *unreadCount = [channel unreadCount];
        return callback(@[[NSNull null], unreadCount]);
      } else {
        return callback(@[@"channel not found", [NSNull null]]);
      }
    }];
  } else {
    ALChannel *alChannel = [channelService getChannelByKey:groupId];
    NSNumber *unreadCount = [alChannel unreadCount];
    return callback(@[[NSNull null], unreadCount]);
  }
}

RCT_EXPORT_METHOD(totalUnreadCount:(RCTResponseSenderBlock)callback){

  ALUserService *alUserService = [[ALUserService alloc] init];

  if (![ALUserDefaultsHandler isInitialMessageListCallDone]) {
    ALMessageDBService *messageDBService = [[ALMessageDBService alloc] init];
    [messageDBService getLatestMessages:NO
                  withCompletionHandler:^(NSMutableArray *messageListArray, NSError *error) {
      if (error) {
        return callback(@[@"Error", [NSNull null]]);
      } else {
        NSNumber * totalUnreadCount = [alUserService getTotalUnreadCount];
        return callback(@[[NSNull null], totalUnreadCount]);
      }
    }];
  } else {
    NSNumber * totalUnreadCount = [alUserService getTotalUnreadCount];
    return callback(@[[NSNull null], totalUnreadCount]);
  }
}

RCT_EXPORT_METHOD(isUserLogIn:(RCTResponseSenderBlock)callback) {
  NSString *response = [ALUserDefaultsHandler isLoggedIn] ? @"true" : @"false";
  return callback(@[response]);
}

//===================================== Log Out ===================================================
/**
 *  Logout users
 *
 */


RCT_EXPORT_METHOD(logoutUser:(RCTResponseSenderBlock)callback) {
  ALRegisterUserClientService *alRegisterUserClientService = [[ALRegisterUserClientService alloc]init];

  [alRegisterUserClientService logoutWithCompletionHandler:^(ALAPIResponse *response, NSError *error) {

    return callback(@[[NSNull null],@"success"]);
  }];

}

RCT_EXPORT_METHOD(hideCreateGroupIcon:(BOOL) hide) {
  [ALApplozicSettings setGroupOption: !hide];
}

RCT_EXPORT_METHOD(sendMessage: (nonnull NSString *)messageJson
                  andCallback:(RCTResponseSenderBlock)callback) {
  return callback(@[@"Error", @"Method not implemented"]);
}

RCT_EXPORT_METHOD(showOnlyMyContacts:(BOOL)showOnlyMyContacts) {
  [ALApplozicSettings setFilterContactsStatus:NO];

  if (showOnlyMyContacts) {
    NSMutableArray *array = [NSMutableArray new];
    [array addObject:[NSNumber numberWithInt:1]];
    [ALApplozicSettings setContactTypeToFilter: array];
  } else {
    [ALApplozicSettings setContactTypeToFilter: nil];
  }
}

RCT_EXPORT_METHOD(addContacts: (nonnull NSString *)contactJson
                  andCallback:(RCTResponseSenderBlock)callback) {
  contactJson = [contactJson stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
  contactJson = [NSString stringWithFormat:@"%@",contactJson];

  NSError* error;
  NSData *jsonData = [contactJson dataUsingEncoding:NSUTF8StringEncoding];
  id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error:&error];
  NSArray * jsonArray = [NSArray arrayWithArray:(NSArray *)jsonObject];
  if (jsonArray.count) {
    NSDictionary *JSONDictionary = (NSDictionary *)jsonObject;
    ALContactService *alContactService = [[ALContactService alloc] init];
    for (NSDictionary *theDictionary in JSONDictionary) {
      ALContact *userDetail = [[ALContact alloc] initWithDict:theDictionary];
      if (theDictionary[@"contactType"] != nil) {
        userDetail.contactType = theDictionary[@"contactType"];
      }
      if (theDictionary[@"fullName"] != nil){
        userDetail.displayName = theDictionary[@"fullName"];
      }
      if (theDictionary[@"imageURL"] != nil) {
        userDetail.contactImageUrl = theDictionary[@"imageURL"];
      }
      [alContactService updateOrInsert:userDetail];
    }
    return callback(@[@"Success", @"Contacts inserted"]);
  }
}

RCT_EXPORT_METHOD(setAttachmentOptions: (NSDictionary *)settingsDictionary) {
  NSMutableArray *settingsArray =  [NSMutableArray new];
  if ([settingsDictionary valueForKey:@":camera"] != nil && [settingsDictionary[@":camera"]  isEqual: @NO]) {
    [settingsArray addObject:@":camera"];
  }
  if ([settingsDictionary valueForKey:@":file"] != nil && [[settingsDictionary valueForKey:@":file"]  isEqual: @NO]) {
    [settingsArray addObject:@":gallery"];
  }
  if ([settingsDictionary valueForKey:@":audio"] != nil && [settingsDictionary[@":audio"]  isEqual: @NO]) {
    [settingsArray addObject:@":audio"];
  }
  if ([settingsDictionary valueForKey:@":video"] != nil && [settingsDictionary[@":video"]  isEqual: @NO]) {
    [settingsArray addObject:@":video"];
  }
  if ([settingsDictionary valueForKey:@":location"] != nil && [settingsDictionary[@":location"]  isEqual: @NO]) {
    [settingsArray addObject:@":location"];
  }
  if ([settingsDictionary valueForKey:@":blockUser"] != nil && [settingsDictionary[@":blockUser"]  isEqual: @NO]) {
    [settingsArray addObject:@":blockUser"];
  }
  if ([settingsDictionary valueForKey:@":contact"] != nil && [settingsDictionary [@":contact"] isEqual: @NO]) {
    [settingsArray addObject:@":shareContact"];
  }
  if ([settingsDictionary valueForKey:@":attachmentbutton"] != nil && [settingsDictionary[@":attachmentbutton"] isEqual: @NO]) {
    [settingsArray addObject:@":attachmentbutton"];
  }
  if (settingsArray.count) {
    NSArray *attachmentOptionToHide = [NSArray arrayWithArray:settingsArray];
    [ALApplozicSettings setHideAttachmentsOption:attachmentOptionToHide];
  }
}

-(NSString *)getJsonString:(id)Object {

  NSError *error;
  NSString *jsonString;
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:Object
                                                     options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                       error:&error];

  if (!jsonData) {
    NSLog(@"Got an error: %@", error);
  } else {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  }
  return jsonString;
}


@end
