//
//  HWMTransparentWindowController.m
//  HWMUISDKNativeDemo
//
//

#import "HWMTransparentWindowController.h"
#import "HWMInputView.h"
#import <HWMUISDK/HWMUISDK.h>

@interface HWMTransparentWindowController ()

@property (nonatomic, strong) HWMInputView *transparentWndInputView;
@property (nonatomic, strong) NSTextField *descLabel;
@property (nonatomic, strong) NSButton *confirmBtn;
@property (nonatomic, strong) NSButton *windowListButton;

@end

static pid_t appPid;

@implementation HWMTransparentWindowController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.transparentWndInputView];
    [self.transparentWndInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(60);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(300);
    }];
    [self.view addSubview:self.descLabel];
    [self.descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.transparentWndInputView.mas_bottom);
        make.leading.width.height.equalTo(self.transparentWndInputView);
    }];
    [self.view addSubview:self.confirmBtn];
    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.descLabel.mas_bottom);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(250);
    }];
    [self.view addSubview:self.windowListButton];
    [self.windowListButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.confirmBtn.mas_bottom).offset(50);
        make.centerX.equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(NSMakeSize(250, 35));
    }];
}

- (void)confirmBtnClick {
    NSString *text = self.transparentWndInputView.textField.stringValue;
    text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (!text || text.length == 0) {
        [self handleTransparentWnd:[NSArray array]];
        return;
    }
    NSArray *array = [text componentsSeparatedByString:@","];
    if (array.count > 4) {
        [HWMConsoleManager shareInstance].console = @"透明窗口id输入不合法";
        return;
    }
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSMutableArray *windowIds = [NSMutableArray array];
    if (array.count > 0) {
        for (NSString *str in array) {
            NSNumber *number = [formatter numberFromString:str];
            if (number) {
                [windowIds addObject:number];
            } else {
                [HWMConsoleManager shareInstance].console = @"透明窗口id输入不合法";
                return;
            }
        }
    }
    [self handleTransparentWnd:windowIds];
}

- (void)handleTransparentWnd:(NSArray *)windowIds {
    HWMUISDKTransparentWndInfoModel *info = [[HWMUISDKTransparentWndInfoModel alloc] init];
    info.handle = windowIds;
    HWMUISDKSDKERR result = [[HWMSdk getOpenApi] setTransparentWndWithInfo:info];
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"设置透明弹窗：%ld", result];
}

- (void)checkWindowList {
    NSArray *windows = [self fetchCGWindows];
    NSData *data = [NSJSONSerialization dataWithJSONObject:windows options:NSJSONWritingPrettyPrinted error:nil];
    [HWMConsoleManager shareInstance].console = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

- (NSArray *)fetchCGWindows {
    appPid = [[NSProcessInfo processInfo] processIdentifier];
    
    //获取系统窗口
    CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionAll, kCGNullWindowID);
    if(NULL == windowList) {//CF函数调用无安全防护，CFArrayGetCount传参NULL，会闪退
        return nil;
    }

    //获取有效窗口
    NSMutableArray *prunedWindowInfos = [NSMutableArray array];
    CFArrayApplyFunction(windowList, CFRangeMake(0, CFArrayGetCount(windowList)), &WindowListOfPidUnSystemApplierFunction, (__bridge void *)(prunedWindowInfos));
    CFRelease(windowList);
    return prunedWindowInfos;
}

void WindowListOfPidUnSystemApplierFunction(const void *inputDictionary, void *context);
void WindowListOfPidUnSystemApplierFunction(const void *inputDictionary, void *context)
{
    NSDictionary *entry = (__bridge NSDictionary *)inputDictionary;
    NSMutableArray *prunedWindowInfos = (__bridge NSMutableArray *)context;

    //排除非本pid的窗口
    pid_t pid = [[entry objectForKey:(id)kCGWindowOwnerPID] unsignedIntValue];
    if (pid != appPid) return;
    
    CGRect bounds;
    CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[entry objectForKey:(id)kCGWindowBounds], &bounds);
    if (bounds.size.height < 22 || bounds.size.width < 22) {
        return;
    }
    
    BOOL isOnScreen = [[entry objectForKey:(id)kCGWindowIsOnscreen] boolValue];
    if (isOnScreen) {
        NSString *windowName = [entry objectForKey:(id)kCGWindowName];
        NSString *appName = [entry objectForKey:(id)kCGWindowOwnerName];
        CGWindowID windowID = [[entry objectForKey:(id)kCGWindowNumber] unsignedIntValue];
        NSRect windowFrame = NSRectFromCGRect(bounds);
        NSMutableDictionary *windowInfo = [NSMutableDictionary dictionary];
        if (windowName) {
            windowInfo[@"windowName"] = windowName;
        }
        if (appName) {
            windowInfo[@"appName"] = appName;
        }
        windowInfo[@"windowId"] = @(windowID);
        windowInfo[@"windowFrame"] = NSStringFromRect(windowFrame);
        [prunedWindowInfos addObject:windowInfo];
    }
}

- (HWMInputView *)transparentWndInputView {
    if (!_transparentWndInputView) {
        _transparentWndInputView = [[HWMInputView alloc] init];
        _transparentWndInputView.title = @"窗口列表";
    }
    return _transparentWndInputView;
}

- (NSTextField *)descLabel {
    if (!_descLabel) {
        _descLabel = [NSTextField hwm_fieldWithTitle:@"透明窗口id列表，以英文逗号隔开，不超过4个" titleColor:[NSColor colorWithRGB:0x999999] font:[NSFont systemFontOfSize:13]];
    }
    return _descLabel;
}

- (NSButton *)confirmBtn {
    if (!_confirmBtn) {
        _confirmBtn = [NSButton buttonWithTitle:@"确定" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(confirmBtnClick)];
        _confirmBtn.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
        _confirmBtn.layer.cornerRadius = 4.0;
        _confirmBtn.layer.masksToBounds = YES;
    }
    return _confirmBtn;
}

- (NSButton *)windowListButton {
    if (!_windowListButton) {
        _windowListButton = [NSButton buttonWithTitle:@"打印本App所有窗口" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(checkWindowList)];
        _windowListButton.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
        _windowListButton.layer.cornerRadius = 4.0;
        _windowListButton.layer.masksToBounds = YES;
    }
    return _windowListButton;
}

@end
