//
//  lovenseUnityPlugins.m
//  UnityFramework
//
//  Created by chonghang on 2023/6/2.
//

#import <Foundation/Foundation.h>
#import <Lovense/Lovense.h>
#import "UnityInterface.h"
@interface LovenseUnityPlugin:NSObject
+(instancetype) getInstance;
@property NSString* name;
@end

@implementation LovenseUnityPlugin
static LovenseUnityPlugin* ins;
+(instancetype) getInstance {
    if(ins == nil) {
        ins = [[self alloc] init];
    }
    return ins;
}

-(void)setDevelopeToken:(NSString *)token withGameName:(NSString*) name {
	self.name = name;
    [[Lovense shared] setDeveloperToken:token];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toyConnectSuccessNotification:)
    name:kToyConnectSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toyConnectFailNotification:)
    name:kToyConnectFailNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toyConnectBreakNotification:)
    name:kToyConnectBreakNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toyScanSuccessNotification:)
    name:kToyScanSuccessNotification object:nil];      //Scanning toy success notification
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toyCallbackNotificationBattery:)
    name:kToyCallbackNotificationBattery object:nil];      //Scanning toy success notification
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toyCallbackNotificationDeviceType:)
    name:kToyCallbackNotificationDeviceType object:nil];      //Scanning toy success notification
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toyCommandCallbackNotificationAtSuccess:)
    name:kToyCommandCallbackNotificationAtSuccess object:nil];      //Scanning toy success notification
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toySendCommandErrorNotification:)
    name:kToySendCommandErrorNotification object:nil];      //Scanning toy success notification
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toyCommandCallbackNotificationAtError:)
    name:kToyCommandCallbackNotificationAtError object:nil];      //Scanning toy success notification
    NSLog(@"init success");
}

-(void) toyConnectSuccessNotification:(NSNotification *) noti {
    NSDictionary * dict = [noti object];
    LovenseToy *toy = [dict objectForKey:@"toy"];
    UnitySendMessage([self.name UTF8String], "kToyConnectSuccessNotification", [[toy identifier] UTF8String]);
}

-(void) toyConnectFailNotification:(NSNotification *) noti{
    NSDictionary * dict = [noti object];
    LovenseToy *toy = [dict objectForKey:@"toy"];
    NSString *error = [dict objectForKey:@"error"];
    NSString *params = [NSString stringWithFormat:@"%@,%@",[toy identifier],error];
    UnitySendMessage([self.name UTF8String], "kToyConnectFailNotification", [params UTF8String]);
}

-(void) toyConnectBreakNotification:(NSNotification *) noti{
    NSDictionary * dict = [noti object];
    LovenseToy *toy = [dict objectForKey:@"toy"];
    NSError *error = [dict objectForKey:@"error"];
    NSString *params = [NSString stringWithFormat:@"%@,%@",[toy identifier],[error localizedDescription]];
    UnitySendMessage([self.name UTF8String], "kToyConnectBreakNotification", [params UTF8String]);
}

-(void) toyCallbackNotificationBattery:(NSNotification *) noti {
    NSDictionary * dict = [noti object];
    LovenseToy *toy = [dict objectForKey:@"receiveToy"];
    NSString *battery = [dict objectForKey:@"battery"];
    NSString *params = [NSString stringWithFormat:@"%@,%@",[toy identifier],battery];
    UnitySendMessage([self.name UTF8String], "kToyCallbackNotificationBattery", [params UTF8String]);
}

-(void) toyCallbackNotificationDeviceType:(NSNotification *) noti {
    NSDictionary * dict = [noti object];
    LovenseToy *toy = [dict objectForKey:@"receiveToy"];
    NSString *type = [dict objectForKey:@"type"];
    NSString *version = [dict objectForKey:@"version"];
    NSString *macAddress = [dict objectForKey:@"macAddress"];
    NSString *params = [NSString stringWithFormat:@"%@,%@,%@,%@",toy.identifier,type,version,macAddress];
    UnitySendMessage([self.name UTF8String], "kToyCallbackNotificationDeviceType", [params UTF8String]);
}

-(void) toyCommandCallbackNotificationAtSuccess:(NSNotification *) noti {
    NSDictionary * dict = [noti object];
    LovenseToy *toy = [dict objectForKey:@"receiveToy"];
    NSString *type = [dict objectForKey:@"commandType"];
  
    NSString *params = [NSString stringWithFormat:@"%@,%@",[toy identifier],type];
    UnitySendMessage([self.name UTF8String], "kToyCommandCallbackNotificationAtSuccess", [params UTF8String]);
}

-(void) toySendCommandErrorNotification:(NSNotification *) noti {
    NSDictionary * dict = [noti object];
    NSString *errorDesc = [dict objectForKey:@"errorDesc"];
    UnitySendMessage([self.name UTF8String], "kToySendCommandErrorNotification", [errorDesc UTF8String]);
}

-(void) toyCommandCallbackNotificationAtError:(NSNotification *) noti {
    NSDictionary * dict = [noti object];
    LovenseToy *toy = [dict objectForKey:@"receiveToy"];
    NSString *type = [dict objectForKey:@"commandType"];
    NSString *params = [NSString stringWithFormat:@"%@,%@",[toy identifier],type];
    UnitySendMessage([self.name UTF8String], "kToyCommandCallbackNotificationAtError", [params UTF8String]);
}

-(void)toyScanSuccessNotification:(NSNotification *)noti
{
    NSDictionary * dict = [noti object];
    NSArray <LovenseToy*>* toys = [dict objectForKey:@"scanToyArray"];
    NSMutableArray *jsonArray = [NSMutableArray array];
    for (LovenseToy *obj in toys) {
        NSNumber *isFound = [NSNumber numberWithBool:obj.isFound];
        NSNumber *isConnected = [NSNumber numberWithBool:obj.isConnected];
        NSNumber *battery = [NSNumber numberWithInt:obj.battery];
        NSNumber *rssi = [NSNumber numberWithInt:obj.rssi];

        NSDictionary *dict1 = @{@"name": obj.name, @"identifier": obj.identifier,@"type": @"",@"version": @"",@"macAddress": @"",@"isFound": isFound,@"isConnected": isConnected,
                               @"rssi": rssi,@"battery": battery
        };
        [jsonArray addObject:dict1];
    }

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArray options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    UnitySendMessage([self.name UTF8String], "kToyScanSuccessNotification", [jsonString UTF8String]);
}

-(void) onGetToys {
    [[Lovense shared] listToys];
}

-(void)searchToys{
    [[Lovense shared] searchToys];
}

-(void)stopSearch{
    [[Lovense shared] stopSearching];
}

-(void) connectToy:(NSString*)toyId{
   
    [[Lovense shared] connectToy:toyId];
}

-(void) disConnectToy:(NSString*) toyId {
    [[Lovense shared] disconnectToy:(toyId)];
}

-(void) sendCommandWithToyId:(NSString *) toyId withCommandType:(NSInteger) cmdtype withLevelValue:(NSInteger) value {
    
    LovenseCommandType type = (LovenseCommandType) cmdtype;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    switch (type) {
        case COMMAND_ROTATE:
            dic[kSendCommandParamKey_RotateLevel] = @(value);
            break;
        case COMMAND_VIBRATE:
            dic[kSendCommandParamKey_VibrateLevel] = @(value);
            break;
		case COMMAND_FLEXER_VIBRATE:
            dic[kSendCommandParamKey_VibrateLevel] = @(value);
            break;
        case COMMAND_AIR_AUTO:
            dic[kSendCommandParamKey_AirAutoLevel] = @(value);
            break;
        case COMMAND_THRUST:
            dic[kSendCommandParamKey_ThrustingLevel] = @(value);
            break;
        case COMMAND_FLEXER_FINGER:
            dic[kSendCommandParamKey_FingerLevel] = @(value);
            break;
        case COMMAND_VIBRATE1:
            dic[kSendCommandParamKey_VibrateLevel] = @(value);
			 break;
        case COMMAND_VIBRATE2:
            dic[kSendCommandParamKey_VibrateLevel] = @(value);
            break;
		case COMMAND_VIBRATE3:
            dic[kSendCommandParamKey_VibrateLevel] = @(value);
            break;
		
      
        default:
            break;
    }
    [[Lovense shared] sendCommandWithToyId:toyId andCommandType:type andParamDict:dic];
        
}

-(void) sendMultiplyCommandWithToyId:(NSString *) toyId  withLevelValue:(NSString*) value { //format 1,2,3
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    NSArray *array = [value componentsSeparatedByString:@","];
    dic[kSendCommandParamKey_MultiplyLevel] = array;
	
    [[Lovense shared] sendCommandWithToyId:toyId andCommandType:COMMADN_MULTIPLY andParamDict:dic];
}

-(void) SendSolaceCommand:(NSString*) toyId withThrustLevelValue:(NSInteger) valueThrust withDepthLevelValue :(NSInteger) valueDepth{
	
	NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
	 
	dic[kSendCommandParamKey_ThrustingLevel] = @(valueThrust);
	
	dic[kSendCommandParamKey_DepthLevel] = @(valueDepth);
	
	[[Lovense shared] sendCommandWithToyId:toyId andCommandType:COMMAND_SOLACE andParamDict:dic];
}

-(void) showIosAlert:(NSString*) title withMessage:(NSString*) message withButtonTitle:(NSString*) buttonTitle {
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:nil otherButtonTitles:buttonTitle, nil];
    [alertView show];
}

@end

extern "C" {
    extern void setDevelopeToken(const char *t,const char *n) {
        NSString *token = [NSString stringWithUTF8String:t];
        NSString *name = [NSString stringWithUTF8String:n];
        
        [[Lovense shared] setDeveloperToken:token];
        [[LovenseUnityPlugin getInstance] setDevelopeToken:token withGameName:name];
    }

extern void searchToys() {
    [[LovenseUnityPlugin getInstance] searchToys];
}

extern void stopSearch() {
    [[LovenseUnityPlugin getInstance] stopSearch];
}

extern void connectToy(const char *t) {
    NSString *toyId = [NSString stringWithUTF8String:t];
    [[LovenseUnityPlugin getInstance] connectToy:toyId];
}

extern void disConnectToy(const char *t) {
    NSString *toyId = [NSString stringWithUTF8String:t];
    [[LovenseUnityPlugin getInstance] disConnectToy:toyId];
}

extern void sendCommandWithToyId(const char *t,const int *cmdtype,const int *v) {
    
    NSString *toyId = [NSString stringWithUTF8String:t];
    NSInteger type =(NSInteger) cmdtype;
    NSInteger value = (NSInteger) v;
    [[LovenseUnityPlugin getInstance] sendCommandWithToyId:toyId withCommandType:type withLevelValue:value];
}

extern void SendSolaceCommand(const char *t,const int *vThrust,const int *vDepth) {
	NSString *toyId = [NSString stringWithUTF8String:t];
    NSInteger valueThrust =(NSInteger) vThrust;
    NSInteger valueDepth = (NSInteger) vDepth;
	[[LovenseUnityPlugin getInstance] SendSolaceCommand:toyId withThrustLevelValue:valueThrust withDepthLevelValue:valueDepth];
}

extern void sendMultiplyCommandWithToyId(const char *t, const char *value) {
	NSString *toyId = [NSString stringWithUTF8String:t];
    NSString *multiplyValue =[NSString stringWithUTF8String:value];
	[[LovenseUnityPlugin getInstance] sendMultiplyCommandWithToyId:toyId  withLevelValue:multiplyValue];
}

extern void showIosAlert(const char *ctitle,const char *cmessage,const char *cbuttonTitle) {
    NSString *title = [NSString stringWithUTF8String:ctitle];
    NSString *message = [NSString stringWithUTF8String:cmessage];
    NSString *buttonTitle = [NSString stringWithUTF8String:cbuttonTitle];
    [[LovenseUnityPlugin getInstance] showIosAlert:title withMessage:message withButtonTitle:buttonTitle ];
}
}
