/*
 *    	Copyright 2015-2016 GetSocial B.V.
 *
 *	Licensed under the Apache License, Version 2.0 (the "License");
 *	you may not use this file except in compliance with the License.
 *	You may obtain a copy of the License at
 *
 *    	http://www.apache.org/licenses/LICENSE-2.0
 *
 *	Unless required by applicable law or agreed to in writing, software
 *	distributed under the License is distributed on an "AS IS" BASIS,
 *	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *	See the License for the specific language governing permissions and
 *	limitations under the License.
 */

#import "GetSocialCurrentUserCordova.h"

@implementation GetSocialCurrentUserCordova

static ResolveUserIdentityConflictBlock userIdentityResolver = nil;

+ (ResolveUserIdentityConflictBlock)userIdentityResolver
{
    return userIdentityResolver;
}

+ (void)setUserIdentityResolver:(ResolveUserIdentityConflictBlock) block
{
    userIdentityResolver = block;
}

NSString *const kCustomProvider = @"custom";


-(NSDictionary*) getReturnedUserData:(BOOL) isConflict andResolve:(int) resolveStatus {
    return  @{@"serializedUser":[[GetSocial sharedInstance].currentUser serialize], @"isConflict":[NSNumber numberWithBool:isConflict], @"resolveStatus":[NSNumber numberWithInt:resolveStatus]};
}

-(void)resolveUserIdentityConflict:(CDVInvokedUrlCommand *)command {
    NSString *callbackId = [command callbackId];
    NSString *resolution = [[command arguments] objectAtIndex:0];
    
    if([GetSocialCurrentUserCordova userIdentityResolver] != nil) {
        if([resolution isEqualToString:@"remote"]) {
            userIdentityResolver(GetSocialAddIdentityConflictResolutionStrategyRemote);
            [self successWithCallbackId:callbackId];
        } else if([resolution isEqualToString:@"current"]) {
            userIdentityResolver(GetSocialAddIdentityConflictResolutionStrategyCurrent);
            [self successWithCallbackId:callbackId];
        }
    }
    
    [self errorWithMsg:@"Not found user identity conflicts" andCallbackId:callbackId];
}

- (void)setDisplayName:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];
    NSString *displayName = [[command arguments] objectAtIndex:0];

    [[GetSocial sharedInstance]
            .currentUser setDisplayName:displayName
        success:^{
            [self successWithNSStringResult:[[GetSocial sharedInstance].currentUser serialize] andCallbackId:callbackId];
        }
        failure:^(NSError *error) {
            NSString *errorMsg =
                [NSString stringWithFormat:@"Cannot change user display name to %@. Reason %@", displayName, [error localizedDescription]];

            [self errorWithMsg:errorMsg andCallbackId:callbackId];

        }];
}

- (void)setAvatarUrl:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];
    NSString *avatarUrl = [[command arguments] objectAtIndex:0];

    [[GetSocial sharedInstance]
            .currentUser setAvatarUrl:avatarUrl
        success:^{
            [self successWithNSStringResult:[[GetSocial sharedInstance].currentUser serialize] andCallbackId:callbackId];
        }
        failure:^(NSError *error) {
            NSString *errorMsg = [NSString stringWithFormat:@"Cannot change avatar to %@. Reason %@", avatarUrl, [error localizedDescription]];
            [self errorWithMsg:errorMsg andCallbackId:callbackId];
        }];
}

- (void)addFbUserIdentity:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];
    NSString *token = [[command arguments] objectAtIndex:0];

    [GetSocialCurrentUserCordova setUserIdentityResolver:nil];
    
    GetSocialCurrentUser *currentUser = [GetSocial sharedInstance].currentUser;
    if (![currentUser userIdForProvider:kGetSocialProviderFacebook])
    {
                GetSocialUserIdentity *identity = [GetSocialUserIdentity facebookIdentityWithToken:token];

                [currentUser addUserIdentity:identity
                    complete:^(GetSocialAddIdentityResult result) {
                        NSLog(@"App FB Auth -> GetSocial Add FB User Identity result: %@", [self userIdentityResultString:result]);

                        [self successWithDictionaryResult:[self getReturnedUserData:NO andResolve:result] andCallbackId:callbackId];
                    }
                    failure:^(NSError *error) {
                        NSLog(@"App FB Auth -> GetSocial Add FB User Identity failed: %@.", [error localizedDescription]);

                        [self errorWithMsg:[error localizedDescription] andCallbackId:callbackId];

                    }
                    conflict:^(GetSocialUser *currentUser, GetSocialUser *remoteUser,
                               void (^resolve)(GetSocialAddIdentityConflictResolutionStrategy strategy)) {
                        
                        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self getReturnedUserData:YES andResolve:0]];
                        [result setKeepCallback:[NSNumber numberWithBool:YES]];
                        [self.commandDelegate sendPluginResult:result callbackId:callbackId];
                        
                        [GetSocialCurrentUserCordova setUserIdentityResolver:resolve];
                    }];
    }
    else
    {
        [self errorWithMsg:@"User has already a Facebook identity." andCallbackId:callbackId];
    }
}

- (NSString *)userIdentityResultString:(GetSocialAddIdentityResult)result
{
    switch (result)
    {
        case GetSocialAddIdentityResultIdentityAdded:
            return @"Identity Added";
            break;

        case GetSocialAddIdentityResultConflictResolvedWithCurrent:
            return @"Conflict Resolved with Current";
            break;

        case GetSocialAddIdentityResultConflictResolvedWithRemote:
            return @"Conflict Resolved with Remote";
            break;

        default:
            return @"";
            break;
    }
}

- (void)removeFbUserIdentity:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];

    GetSocialCurrentUser *currentUser = [GetSocial sharedInstance].currentUser;
    if ([currentUser userIdForProvider:kGetSocialProviderFacebook])
    {
        [currentUser removeUserIdentityForProvider:kGetSocialProviderFacebook
            success:^{
                NSLog(@"UserIdentity removed for Provider %@.", kGetSocialProviderFacebook);
                [self successWithNSStringResult:[[GetSocial sharedInstance].currentUser serialize] andCallbackId:callbackId];
            }
            failure:^(NSError *error) {
                NSLog(@"Failed to remove UserIdentity for Provider %@, error: %@", kGetSocialProviderFacebook, [error localizedDescription]);
                [self errorWithMsg:[error localizedDescription] andCallbackId:callbackId];
            }];
    }
    else
    {
        [self errorWithMsg:@"User doesn't have UserIdentity for Provider facebook." andCallbackId:callbackId];
    }
}

- (void)addUserIdentity:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];
    NSString *userId = [[command arguments] objectAtIndex:0];
    NSString *token = [[command arguments] objectAtIndex:1];

    if (![userId isEqualToString:@""] && ![token isEqualToString:@""])
    {
        [GetSocialCurrentUserCordova setUserIdentityResolver:nil];
        
        GetSocialUserIdentity *identity = [GetSocialUserIdentity identityWithProvider:kCustomProvider userId:userId token:token];
        GetSocialCurrentUser *currentUser = [GetSocial sharedInstance].currentUser;

        [currentUser addUserIdentity:identity
            complete:^(GetSocialAddIdentityResult result) {
                NSLog(@"User identity added %@ for Provider '%@', result: %@", userId, kCustomProvider, [self userIdentityResultString:result]);
                
                [self successWithDictionaryResult:[self getReturnedUserData:NO andResolve:result] andCallbackId:callbackId];
            }
            failure:^(NSError *error) {
                NSString *errorMsg = [NSString stringWithFormat:@"Failed to add user identity %@ for Provider '%@', error: %@", userId,
                                                                kCustomProvider, [error localizedDescription]];
                NSLog(@"%@", errorMsg);
                [self errorWithMsg:errorMsg andCallbackId:callbackId];

            }
            conflict:^(GetSocialUser *currentUser, GetSocialUser *remoteUser,
                       void (^resolve)(GetSocialAddIdentityConflictResolutionStrategy strategy)) {
                
                CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self getReturnedUserData:YES andResolve:0]];
                [result setKeepCallback:[NSNumber numberWithBool:YES]];
                [self.commandDelegate sendPluginResult:result callbackId:callbackId];
                
                [GetSocialCurrentUserCordova setUserIdentityResolver:resolve];
            }];
    }
    else
    {
        [self errorWithMsg:@"Failed to add User Identity, User Id and Token fields can\'t be empty" andCallbackId:callbackId];
    }
}

- (void)removeUserIdentity:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];
    NSString *providerId = [[command arguments] objectAtIndex:0];

    GetSocialCurrentUser *currentUser = [GetSocial sharedInstance].currentUser;
    if ([currentUser userIdForProvider:providerId])
    {
        [currentUser removeUserIdentityForProvider:providerId
            success:^{
                NSLog(@"User identity removed for Provider '%@'", providerId);
                [self successWithNSStringResult:[[GetSocial sharedInstance].currentUser serialize] andCallbackId:callbackId];
            }
            failure:^(NSError *error) {
                NSLog(@"Failed to remove user identity for Provider '%@', error: %@", providerId, [error localizedDescription]);
                [self errorWithMsg:[NSString stringWithFormat:@"Failed to remove user identity for Provider '%@', error: %@", providerId,
                                                              [error localizedDescription]]
                     andCallbackId:callbackId];

            }];
    }
    else
    {
        NSLog(@"User doesn't have user identity for Provider '%@'", providerId);
        [self errorWithMsg:[NSString stringWithFormat:@"User doesn't have user identity for Provider '%@'", providerId] andCallbackId:callbackId];
    }
}

- (void)reset:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];

    [[GetSocial sharedInstance]
            .currentUser resetWithSuccess:^{
        NSLog(@"User was reset.", nil);

        [self successWithNSStringResult:[[GetSocial sharedInstance].currentUser serialize] andCallbackId:callbackId];
    }
        failure:^(NSError *error) {
            NSString *errMsg = [NSString stringWithFormat:@"Couldn't reset user. Reason %@", [error localizedDescription]];
            [self errorWithMsg:errMsg andCallbackId:callbackId];
        }];
}


@end
