//
//  InMobiPlugin.m
//  Unity-iPhone
//
//  Created by Vineet Srivastava on 11/22/16.
//
//

#import "InMobiPlugin.h"
#import "UnityAppController.h"
#import "USDKCommonTypes.h"

NSString * const IM_UNITY_MIN_IOS_VERSION_SUPPORTED_BY_SDK = @"9.0";

@interface UIView (unityStub)
@property UILayoutGuide *safeAreaLayoutGuide;
@end

static BOOL IsOperatingSystemAtLeastVersion(NSInteger majorVersion) {
    NSProcessInfo *processInfo = NSProcessInfo.processInfo;
    if ([processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)]) {
        // iOS 8+.
        NSOperatingSystemVersion version = {majorVersion};
        return [processInfo isOperatingSystemAtLeastVersion:version];
    } else {
        // pre-iOS 8. App supports iOS 7+, so this process must be running on iOS 7.
        return majorVersion >= 7;
    }
}

static CGFloat FullSafeWidthLandscape(void) {
    CGRect screenBounds = [UIScreen mainScreen].bounds;
    if (IsOperatingSystemAtLeastVersion(11)) {
        CGRect safeFrame = [UIApplication sharedApplication].keyWindow.safeAreaLayoutGuide.layoutFrame;
        if (!CGSizeEqualToSize(safeFrame.size, CGSizeZero)) {
            screenBounds = safeFrame;
        }
    }
    return MAX(CGRectGetWidth(screenBounds), CGRectGetHeight(screenBounds));
}


@implementation InMobiPlugin

+ (UIViewController *)unityGLViewController {
    return ((UnityAppController *)[UIApplication sharedApplication].delegate).rootViewController;
}


+ (NSString*)JSONfromObject:(id)object
{
    if( [NSJSONSerialization isValidJSONObject:object] )
    {
        NSError *error = nil;
        NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:&error];
        
        if( error )
            NSLog( @"error serializing object to JSON: %@", error );
        
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    
    return @"{}";
}


+ (NSDictionary *)convertStringToDictionary:(NSString *)string {
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    if( [NSJSONSerialization isValidJSONObject:data] )
    {
        NSError *error = nil;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        
        if( !error ) {
            return dict;
        }
    }
    return nil;
}

+ (void)positionView:(UIView *)view
        inParentView:(UIView *)parentView
          adPosition:(int)adPosition {
    CGRect parentBounds = parentView.bounds;
    if (IsOperatingSystemAtLeastVersion(11)) {
        CGRect safeAreaFrame = parentView.safeAreaLayoutGuide.layoutFrame;
        if (!CGSizeEqualToSize(CGSizeZero, safeAreaFrame.size)) {
            parentBounds = safeAreaFrame;
        }
    }
    CGFloat top = CGRectGetMinY(parentBounds) + CGRectGetMidY(view.bounds);
    CGFloat left = CGRectGetMinX(parentBounds) + CGRectGetMidX(view.bounds);

    CGFloat bottom = CGRectGetMaxY(parentBounds) - CGRectGetMidY(view.bounds);
    CGFloat right = CGRectGetMaxX(parentBounds) - CGRectGetMidX(view.bounds);
    CGFloat centerX = CGRectGetMidX(parentBounds);
    CGFloat centerY = CGRectGetMidY(parentBounds);

    // If this view is of greater or equal width to the parent view, do not offset
    // to edge of safe area. Eg for smart banners that are still full screen
    // width.
    if (CGRectGetWidth(view.bounds) >= CGRectGetWidth(parentView.bounds)) {
        left = CGRectGetMidX(parentView.bounds);
    }

    // Similarly for height, if view is of custom size which is full screen
    // height, do not offset.
    if (CGRectGetHeight(view.bounds) >= CGRectGetHeight(parentView.bounds)) {
        top = CGRectGetMidY(parentView.bounds);
    }

    CGPoint center = CGPointMake(centerX, top);
    switch (adPosition) {
        case ASIMAdPositionTopCenter:
            center = CGPointMake(centerX, top);
            break;
        case ASIMAdPositionBottomCenter:
            center = CGPointMake(centerX, bottom);
            break;
        case ASIMAdPositionTopLeft:
            center = CGPointMake(left, top);
            break;
        case ASIMAdPositionTopRight:
            center = CGPointMake(right, top);
            break;
        case ASIMAdPositionBottomLeft:
            center = CGPointMake(left, bottom);
            break;
        case ASIMAdPositionBottomRight:
            center = CGPointMake(right, bottom);
            break;
        case ASIMAdPositionCenter:
            center = CGPointMake(centerX, centerY);
            break;
        default:
            break;
    }

    view.center = center;
}

+ (void)positionView:(UIView *)view
        inParentView:(UIView *)parentView
      customPosition:(CGPoint)adPosition {
    CGPoint origin = parentView.bounds.origin;
    if (IsOperatingSystemAtLeastVersion(11)) {
        CGRect safeAreaFrame = parentView.safeAreaLayoutGuide.layoutFrame;
        if (!CGSizeEqualToSize(CGSizeZero, safeAreaFrame.size)) {
            origin = safeAreaFrame.origin;
        }
    }

    CGPoint center = CGPointMake(origin.x + adPosition.x + CGRectGetMidX(view.bounds),
                                 origin.y + adPosition.y + CGRectGetMidY(view.bounds));
    view.center = center;
}


+ (NSString *)checkIfIMSDKInitilisationCanBeProceeded:(NSString *)accountID {
    if (![accountID isKindOfClass:[NSString class]] || ([accountID length] != 32 && [accountID length] != 36)) {
        return @"Invalid account id passed to init. Please provide a valid account id.";
    } else if (![[self class] systemVersionAvailable:IM_UNITY_MIN_IOS_VERSION_SUPPORTED_BY_SDK]) {
        NSString* errorMsg = [NSString stringWithFormat:@"Error initialising InMobi SDK since minimum supported iOS version is %@", IM_UNITY_MIN_IOS_VERSION_SUPPORTED_BY_SDK];
        return errorMsg;
    } else if ([[self class] checkForMultiWindowSupport]) {
        return @"Unable to initialise SDK as Inmobi SDK does not support Multi Window. Please contact your partner manager for further help.";
    }
    return nil;
}

+ (NSString *)checkIfASSDKInitilisationCanBeProceeded:(NSString *)appId {
    if ([appId longLongValue] <= 0) {
        return @"Invalid app id passed to init. Please provide a valid app id.";
    } else if (![[self class] systemVersionAvailable:IM_UNITY_MIN_IOS_VERSION_SUPPORTED_BY_SDK]) {
        NSString* errorMsg = [NSString stringWithFormat:@"Error initialising Aerserv SDK since minimum supported iOS version is %@", IM_UNITY_MIN_IOS_VERSION_SUPPORTED_BY_SDK];
        return errorMsg;
    } else if ([[self class] checkForMultiWindowSupport]) {
        return @"Unable to initialise SDK as Aerserv SDK does not support Multi Window. Please contact your partner manager for further help.";
    }
    return nil;
}

+ (BOOL)systemVersionAvailable:(NSString*)systemVersion {
    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    if ([currSysVer compare:systemVersion options:NSNumericSearch] != NSOrderedAscending){
        return TRUE;
    }
    else {
        return FALSE;
    }
}

+ (BOOL)checkForMultiWindowSupport {
    BOOL result = NO;
    if (@available(iOS 13.0, *)) {
        if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
            if ([[UIApplication sharedApplication] supportsMultipleScenes]) {
                result = YES;
            }
        }
    }
    return result;
}

@end
