#import "TQWebViewPool.h"
#import "TQWKConfigurationFactory.h"
#import "TQWebViewConfig.h"
#import <UIKit/UIKit.h>

@implementation TQWebViewPool {
    /// 预热专用实例（不复用到页面）。
    WKWebView *_pooled;
    BOOL _enabled;
}

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

- (instancetype)init {
    if (self = [super init]) {
        _pooled = nil;
        _enabled = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onMemoryWarning)
                                                     name:UIApplicationDidReceiveMemoryWarningNotification
                                                   object:nil];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setEnabled:(BOOL)enabled {
    _enabled = enabled;
    if (!enabled) {
        [self releasePool];
    }
}

- (void)preCreateWithInjectUserAgent:(BOOL)injectUserAgent userAgentExtra:(NSString *)userAgentExtra {
    if (!_enabled) return;
    [self runOnMain:^{
        [self ensureInstanceWithInjectUserAgent:injectUserAgent userAgentExtra:userAgentExtra];
    }];
}

- (void)warmWithUrl:(NSString *)warmupUrl
    injectUserAgent:(BOOL)injectUserAgent
     userAgentExtra:(NSString *)userAgentExtra {
    if (!_enabled || warmupUrl.length == 0) return;
    [self runOnMain:^{
        WKWebView *wv = [self ensureInstanceWithInjectUserAgent:injectUserAgent userAgentExtra:userAgentExtra];
        NSURL *u = [NSURL URLWithString:warmupUrl];
        if (wv == nil || u == nil) return;
        [wv loadRequest:[NSURLRequest requestWithURL:u]];
    }];
}

- (void)releasePool {
    [self runOnMain:^{
        [self->_pooled stopLoading];
        [self->_pooled loadHTMLString:@"" baseURL:nil];
        self->_pooled = nil;
    }];
}

- (void)onMemoryWarning {
    // 预热实例不复用到页面（天然"不被借出"），直接释放不打断签署；
    // 释放后回调上层重置去重状态，使后续 prewarm 可重新预热。
    [self releasePool];
    if (self.onReleasedByMemoryWarning) {
        self.onReleasedByMemoryWarning();
    }
}

- (WKWebView *)ensureInstanceWithInjectUserAgent:(BOOL)injectUserAgent userAgentExtra:(NSString *)userAgentExtra {
    if (_pooled == nil) {
        WKWebViewConfiguration *conf =
            [TQWKConfigurationFactory makeConfigurationWithInjectUserAgent:injectUserAgent
                                                          userAgentExtra:userAgentExtra];
        _pooled = [[WKWebView alloc] initWithFrame:CGRectZero configuration:conf];
    }
    return _pooled;
}

- (void)runOnMain:(void (^)(void))block {
    if ([NSThread isMainThread]) {
        block();
    } else {
        dispatch_async(dispatch_get_main_queue(), block);
    }
}

@end
