/*
Copyright 2024 New Vector Ltd.
Copyright 2017 Vector Creations Ltd
Copyright (c) 2021 BWI GmbH

SPDX-License-Identifier: AGPL-3.0-only
Please see LICENSE in the repository root for full details.
 */

#import "WebViewViewController.h"
#import "GeneratedInterface-Swift.h"

@interface WebViewViewController ()
{
    // Observe kThemeServiceDidChangeThemeNotification to handle user interface theme change.
    id kThemeServiceDidChangeThemeNotificationObserver;
}

@end

@implementation WebViewViewController

- (void)finalizeInit
{
    [super finalizeInit];
    
    // Setup `MXKViewControllerHandling` properties
    self.enableBarTintColorStatusChange = NO;
    self.rageShakeManager = [RageShakeManager sharedManager];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Observe user interface theme change.
    kThemeServiceDidChangeThemeNotificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kThemeServiceDidChangeThemeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {
        
        [self userInterfaceThemeDidChange];
        
    }];
    [self userInterfaceThemeDidChange];
}

- (void)userInterfaceThemeDidChange
{
    [ThemeService.shared.theme applyStyleOnNavigationBar:self.navigationController.navigationBar];

    self.activityIndicator.backgroundColor = ThemeService.shared.theme.overlayBackgroundColor;
    
    webView.backgroundColor = ThemeService.shared.theme.backgroundColor;

    [self setNeedsStatusBarAppearanceUpdate];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return ThemeService.shared.theme.statusBarStyle;
}

- (void)destroy
{
    if (kThemeServiceDidChangeThemeNotificationObserver)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:kThemeServiceDidChangeThemeNotificationObserver];
        kThemeServiceDidChangeThemeNotificationObserver = nil;
    }
    
    [super destroy];
}

- (void)setURL:(NSString *)URL
{
    if (webView && BWIBuildSettings.shared.enableJSInWebView == false) {
        webView.configuration.preferences.javaScriptEnabled = NO;
    }
    
    [super setURL:URL];
}

- (void)setLocalHTMLFile:(NSString *)localHTMLFile
{
    if (webView && BWIBuildSettings.shared.enableJSInWebView == false) {
        webView.configuration.preferences.javaScriptEnabled = NO;
    }
    
    [super setLocalHTMLFile:localHTMLFile];
}

// bwi #7861 we need to enable javascript only for reauthentication
- (void)enableJavascript:(BOOL)enable {
    if (webView) {
        webView.configuration.preferences.javaScriptEnabled = enable;
    }
}

@end
