#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
typedef void (*onquestionViewErrorDelegate)(const char*);
typedef void (*onCloseQuestionViewDelegate)();

typedef void (*INT_CALLBACK)(int);

@interface BackendWebView: NSObject <UIAlertViewDelegate, WKNavigationDelegate, WKScriptMessageHandler>
{
    INT_CALLBACK alertCallBack;
    NSDate *creationDate;
    INT_CALLBACK shareCallBack;
    WKWebView *webView;
    UIView *totalView;
    UIView *blackBlock;
    UIButton *closeButton;
    
    NSString* clientAppId;
    NSString* gamerIndate;
    
    NSString* htmlPath;
    NSString* indexHtml;
    NSString* listHtml;

    int leftMargin;
    int topMargin;
    int rightMargin;
    int bottomMargin;
    int buttonWeight;
    int questionViewWeight;
}


@property (assign) onquestionViewErrorDelegate onquestionViewErrorHandler;
@property (assign) onCloseQuestionViewDelegate onCloseQuestionViewHandler;


@end

@implementation BackendWebView

static BackendWebView *instance;

+(BackendWebView*) instance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[BackendWebView alloc] init];
    });
    return instance;
}

-(id)init
{
    self = [super init];
    if (self)
        NSLog(@"TheBackendQuestionView was created");
    
    leftMargin = 0;
    topMargin = 0;
    rightMargin = 0;
    bottomMargin = 0;
    buttonWeight = 1;
    questionViewWeight = 11;
    
    return self;
}

-(void)setQuestionViewLayoutForIOS: (int)left top:(int)top right:(int)right bottom:(int)bottom buttonWeight:(int)_buttonWeight questionViewWeight:(int)_questionViewWeight
{
    leftMargin = left;
    topMargin = top;
    rightMargin = right;
    bottomMargin = bottom;
    buttonWeight = _buttonWeight;
    questionViewWeight = _questionViewWeight;
}
-(void)openWebView:(NSString*)_path gameId:(NSString*)_gameId indate:(NSString*)_gamerIndate
{
    try {
        if (webView!=nil)
        {
            NSLog(@"WebView is already created");
            return;
        }
        
        if([self isSdkVersionPossible] == false)
        {
            return;
        }
        UIView *mainView = UnityGetGLView();
        
        
        clientAppId = _gameId;
        gamerIndate = _gamerIndate;
        htmlPath = _path;

        CGRect frame = mainView.frame;
        frame.origin.y += topMargin;
        frame.size.height -= topMargin;
        frame.size.height -= bottomMargin;
        
        frame.origin.x += leftMargin;
        frame.size.width -= leftMargin;
        frame.size.width -= rightMargin;

        totalView = [[UIView alloc] initWithFrame:frame];
        [mainView addSubview:totalView];

        
        float heightPer = totalView.frame.size.height / (buttonWeight + questionViewWeight);
        float buttonHeight = heightPer * buttonWeight;
        float viewHeight = heightPer * questionViewWeight;
        
        // 1. Create a black block view with 1/10 of the screen size
        blackBlock = [[UIView alloc] initWithFrame:CGRectMake(0, 0, totalView.frame.size.width, buttonHeight)];
        blackBlock.backgroundColor = [UIColor darkGrayColor];
        [totalView addSubview:blackBlock]; // Add black block to main view

        NSLog(@"값 : %f", blackBlock.frame.origin.x);
        NSLog(@"값 : %f", blackBlock.frame.origin.y);
        
        // 2. Create a close button
        closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        closeButton.frame = CGRectMake(totalView.frame.size.width - buttonHeight - 5, 0, buttonHeight, buttonHeight); // Adjust the frame as needed
        [closeButton setTitle:@"X" forState:UIControlStateNormal];
        [closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [closeButton addTarget:self action:@selector(closeWebView) forControlEvents:UIControlEventTouchUpInside];
        closeButton.titleLabel.font = [UIFont boldSystemFontOfSize:closeButton.bounds.size.height * 0.7];
        closeButton.titleLabel.adjustsFontSizeToFitWidth = YES;
        closeButton.titleLabel.minimumScaleFactor = 0.5;
        [blackBlock addSubview:closeButton]; // Add close button to black
        
        WKUserContentController *wkusercontentcontroller = [[WKUserContentController alloc] init];
        [wkusercontentcontroller addScriptMessageHandler:self name:@"iosMessage"];
        [wkusercontentcontroller addScriptMessageHandler:self name:@"consoleMessage"];
        
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = wkusercontentcontroller;
        [configuration setValue:@TRUE forKey:@"allowUniversalAccessFromFileURLs"];

        
        webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, buttonHeight, totalView.frame.size.width, viewHeight) configuration:configuration];
        webView.navigationDelegate = self;
        
        NSString *indexFileName = @"BackendQuestionMain.html";
        indexHtml = [NSString stringWithFormat:@"%@%@",htmlPath,indexFileName];
        
        NSString *listFileName = @"BackendQuestionList.html";
        listHtml = [NSString stringWithFormat:@"%@%@",htmlPath,listFileName];
        
        NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:indexHtml]];
        
        [webView loadRequest:req];
        [totalView addSubview:webView];
    }
    catch (NSException* exception) {
        NSLog(@"BackendQuestionView Exception %@" ,exception.reason);
        self.onquestionViewErrorHandler([self charToString:exception.reason]);
        [self closeWebView];
    }
}
- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message
{
    if([message.name isEqualToString:@"consoleMessage"])
    {
        NSLog(@"console.log: %@",message.body);
        return;
    }
    if(![message.name isEqualToString:@"iosMessage"])
    {
        return;
    }
    NSString * order = message.body;
    
    if([order isEqualToString: @"ChangeIndexScene"])
    {
        NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:indexHtml]];
        [webView loadRequest:req];

        
    }
    else if([order isEqualToString: @"ChangeListScene"])
    {
        NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:listHtml]];
        [webView loadRequest:req];

    }
    else if([order isEqualToString:@"SettingIosInfo"])
    {
        NSString *filename = [NSString stringWithFormat:@"iOSSetGameIdAndGamerIndate(\"%@\",\"%@\")",clientAppId,gamerIndate];
        [webView evaluateJavaScript:filename completionHandler:nil];
    }
    else if([order isEqualToString:@"CloseWebView"])
    {
        [self closeWebView];
    }

}

-(char *) charToString:(NSString *)string
{
    const char* stringUTF8 = [string UTF8String];
    char* stringChar = (char*)malloc(strlen(stringUTF8) + 1);
    strcpy(stringChar, stringUTF8);
    return stringChar;
}

-(bool)isWebViewOpen
{
    if(webView == nil)
    {
        return false;
    }
    else
    {
        return true;
    }
}

-(bool)isSdkVersionPossible
{
    NSString* versionString = [[UIDevice currentDevice] systemVersion];
    NSArray *arrString= [versionString componentsSeparatedByString: @"."];

    int intVersion = [[arrString objectAtIndex:0] intValue];
    if(intVersion >= 8)
    {
        return true;
    }
    else
    {
        return false;
    }
}

-(void)closeWebView
{
    if(closeButton!=nil)
    {
        [closeButton removeFromSuperview];
        closeButton = nil;
    }
    
    if(blackBlock!=nil)
    {
        [blackBlock removeFromSuperview];
        blackBlock = nil;
    }
    
    if (webView!=nil)
    {
        [webView removeFromSuperview];
        webView = nil;
    }
    
    if(totalView!=nil)
    {
        [totalView removeFromSuperview];
        totalView = nil;
    }

    self.onCloseQuestionViewHandler();
}

@end

extern "C"
{
    void SetQuestionViewLayoutForIOS(int leftMargin, int topMargin, int rightMargin, int bottomMargin, int buttonWeight, int questionViewWeight)
    {
        
        [[BackendWebView instance] setQuestionViewLayoutForIOS: leftMargin top:topMargin right:rightMargin bottom:bottomMargin buttonWeight:buttonWeight questionViewWeight:questionViewWeight];
    }

    void OpenWebViewForIOS(const char *path, const char* gameId, const char* indate, onquestionViewErrorDelegate handler)
    {
        [BackendWebView instance].onquestionViewErrorHandler = handler;
        [[BackendWebView instance] openWebView:[NSString stringWithUTF8String:path] gameId:[NSString stringWithUTF8String:gameId] indate:[NSString stringWithUTF8String:indate]];
    }
    
    void CloseWebViewForIOS()
    {
        [[BackendWebView instance] closeWebView];
    }

    void SetCloseQuestionViewDelegate(onCloseQuestionViewDelegate handler)
    {
        [BackendWebView instance].onCloseQuestionViewHandler = handler;
    }

    bool IsSdkVersionPossibleForIOS()
    {
        return [[BackendWebView instance] isSdkVersionPossible];
    }

    bool IsWebViewOpenForIOS()
    {
        return [[BackendWebView instance] isWebViewOpen];
    }
}
