//
//  RNTAlanButtonManager.m
//
//  Created by Alan AI, Inc on 30.10.2019.
//

#import "AlanSDK.h"
#import "AlanManager.h"
#import "AlanEventEmitter.h"
#import "RNTAlanButtonManager.h"
#import <React/RCTViewManager.h>
#import <React/RCTUtils.h>
#import "DummyView.h"

@interface RNTAlanButtonManager()
@property BOOL isUpdated;
@property NSLayoutConstraint* b;
@property NSLayoutConstraint* r;
@property NSLayoutConstraint* h;
@property NSLayoutConstraint* w;
@end

@implementation RNTAlanButtonManager

RCT_EXPORT_MODULE(RNTAlanButton)

RCT_CUSTOM_VIEW_PROPERTY(params, NSArray, AlanButton)
{
    AlanButton* alanButton = AlanManager.shared.alanButton;
    if( alanButton != nil )
    {
        self.isUpdated = NO;
        [alanButton removeFromSuperview];
        alanButton = nil;
    }
    
    if (![json isKindOfClass:[NSArray class]])
    {
        return;
    }
    
    NSArray* projectParams = [NSArray arrayWithArray:json];
    if( projectParams.count < 1 )
    {
        return;
    }
    
    if ([projectParams[0] isKindOfClass:[NSNull class]])
    {
        return;
    }
    
    NSString* projectKey = projectParams[0];
    NSString* projectHost = @"v1.alan.app";
    NSString* projectVersion = @"2.9.0";
    NSMutableDictionary* projectData = [NSMutableDictionary new];
    if( projectParams.count > 1 )
    {
        if (![projectParams[1] isKindOfClass:[NSNull class]] && [projectParams[1] isKindOfClass:[NSString class]])
        {
            projectHost = projectParams[1];
        }
    }
    if( projectParams.count > 2 )
    {
        if (![projectParams[2] isKindOfClass:[NSNull class]] && [projectParams[2] isKindOfClass:[NSDictionary class]])
        {
            NSDictionary* dataObject = projectParams[2];
            [projectData addEntriesFromDictionary:dataObject];
        }
    }
    if( projectParams.count > 3 )
    {
        if (![projectParams[3] isKindOfClass:[NSNull class]] && [projectParams[3] isKindOfClass:[NSString class]])
        {
            projectVersion = projectParams[3];
        }
    }

    AlanConfig *config = [[AlanConfig alloc] initWithKey:projectKey host:projectHost dataObject:projectData platform:@"react-native" platformVersion:projectVersion];
    alanButton = [[AlanButton alloc] initWithConfig:config];
    
    if( alanButton == nil )
    {
        return;
    }
    
    UIViewController *presentedViewController = RCTPresentedViewController();
    
    [alanButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [presentedViewController.view addSubview:alanButton];

    self.b = [NSLayoutConstraint constraintWithItem:alanButton attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:presentedViewController.view attribute:NSLayoutAttributeBottom multiplier:1 constant:-40.0];
    self.r = [NSLayoutConstraint constraintWithItem:alanButton attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:presentedViewController.view attribute:NSLayoutAttributeRight multiplier:1 constant:-20];
    self.w = [NSLayoutConstraint constraintWithItem:alanButton attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:64.0];
    self.h = [NSLayoutConstraint constraintWithItem:alanButton attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:64.0];

    [presentedViewController.view addConstraints:@[self.b, self.r, self.w, self.h]];
    [presentedViewController.view bringSubviewToFront:alanButton];
    AlanManager.shared.alanButton = alanButton;
    
    AlanText* alanText = AlanManager.shared.alanText;
    if( alanText != nil )
    {
        [alanText removeFromSuperview];
        alanText = nil;
    }
    alanText = [[AlanText alloc] initWithFrame:CGRectZero];
    
    if( alanText == nil )
    {
        return;
    }
    
    [alanText setTranslatesAutoresizingMaskIntoConstraints:NO];
    [presentedViewController.view addSubview:alanText];
    [presentedViewController.view addConstraints:@[
        [NSLayoutConstraint constraintWithItem:alanText attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:presentedViewController.view attribute:NSLayoutAttributeBottom multiplier:1 constant:-40.0],
        [NSLayoutConstraint constraintWithItem:alanText attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:alanButton attribute:NSLayoutAttributeRight multiplier:1 constant:-20],
        [NSLayoutConstraint constraintWithItem:alanText attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:presentedViewController.view attribute:NSLayoutAttributeLeft multiplier:1 constant:20.0],
        [NSLayoutConstraint constraintWithItem:alanText attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:64.0]
    ]];
    [presentedViewController.view bringSubviewToFront:alanText];
    AlanManager.shared.alanText = alanText;

    __weak typeof(self) weakSelf = self;

    AlanManager.shared.alanButton.onEvent = ^(NSString* payload) {
        if( payload == nil )
        {
            return;
        }
        __strong typeof(self) strongSelf = weakSelf;
        if( strongSelf )
        {
            AlanEventEmitter* eventEmitter = [strongSelf.bridge moduleForClass:[AlanEventEmitter class]];
            if( eventEmitter )
            {
                [eventEmitter sendEventWithName:@"onEvent" body:payload];
            }
        }
    };

    AlanManager.shared.alanButton.onCommand = ^(NSDictionary *command) {
        if( command == nil )
        {
            return;
        }
        __strong typeof(self) strongSelf = weakSelf;
        if( strongSelf )
        {
            AlanEventEmitter* eventEmitter = [strongSelf.bridge moduleForClass:[AlanEventEmitter class]];
            if( eventEmitter )
            {
                [eventEmitter sendEventWithName:@"onCommand" body:command];
            }
        }
    };
    
    AlanManager.shared.alanButton.onButtonState = ^(AlanSDKButtonState state) {
        if (state == AlanSDKButtonStateOnline && !self.isUpdated)
        {
            self.isUpdated = YES;
            dispatch_async(dispatch_get_main_queue(), ^(void){
                self.w.constant = 64.0;
                self.h.constant = 64.0;
                [AlanManager.shared.alanButton.layer removeAllAnimations];
            });
        }
        
        __strong typeof(self) strongSelf = weakSelf;
        if( strongSelf )
        {
            NSString* stringState = [strongSelf stateToString:state];
            AlanEventEmitter* eventEmitter = [strongSelf.bridge moduleForClass:[AlanEventEmitter class]];
            if( eventEmitter )
            {
                [eventEmitter sendEventWithName:@"onButtonState" body:stringState];
            }
        }
    };
}

- (UIView *)view
{
    return [DummyView new];
}

- (NSString*)stateToString:(AlanSDKButtonState)state
{
    switch (state)
    {
        case AlanSDKButtonStateOffline:
            return @"OFFLINE";
        case AlanSDKButtonStateConnecting:
            return @"CONNECTING";
        case AlanSDKButtonStateListen:
            return @"LISTEN";
        case AlanSDKButtonStateProcess:
            return @"PROCESS";
        case AlanSDKButtonStateReply:
            return @"REPLY";
        case AlanSDKButtonStateOnline:
            return @"ONLINE";
        case AlanSDKButtonStateIdle:
            return @"IDLE";
        default:
            return @"UNKNOWN";
    }
}

@end

