////////////////////////////////////////////////////////////////////////////////
// CONFIDENTIAL and PROPRIETARY software of Magewell Electronics Co., Ltd.
// Copyright (c) 2011-2019 Magewell Electronics Co., Ltd. (Nanjing)
// All rights reserved.
// This copyright notice MUST be reproduced on all authorized copies.
////////////////////////////////////////////////////////////////////////////////

#import "ViewController.h"
#import <mach/mach.h>
#import <mach/mach_time.h>
#import <mach-o/dyld.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <queue>
#import "APITest.h"
#import "MWCaptureUtil.h"
#import "MWCaptureView.h"


@interface ViewController ()<MWCaptureViewDelegate>
{

}
@property(nonatomic,strong)MWCaptureView   *captureView1;
@property(nonatomic,strong)MWCaptureView   *captureView2;
@property(nonatomic,strong)NSMutableArray<NSLayoutConstraint *> *constraintList;

@end

@implementation ViewController
- (void)relaodRecordMenu
{
    if (!self.captureView1 || ![self.captureView1 isCapturing]) {
        self.startRecordItem.enabled = NO;
        self.stopRecordItem.enabled = NO;
    } else if ([self.captureView1 isRecording]) {
        self.startRecordItem.enabled = NO;
        self.stopRecordItem.enabled = YES;
    } else {
        self.startRecordItem.enabled = YES;
        self.stopRecordItem.enabled = NO;
    }
}

- (void)startRecord:(NSMenuItem *)menuItem {
    BOOL canStart = YES;
    if (self.captureView1 && [self.captureView1 isDoingContinuousAutoSwitch]) {
        canStart = NO;
    }
    if (self.captureView2 && [self.captureView2 isDoingContinuousAutoSwitch]) {
        canStart = NO;
    }
    if (!canStart) {
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:@"AVCapture"];
        [alert setInformativeText:@"Please stop continuous auto switching first"];
        [alert setAlertStyle:NSAlertStyleWarning];
        
        if (alert) {
            [alert runModal];
            return;
        }
    }
    struct timeval tv = { 0 }; char date[32] = {0};
    gettimeofday(&tv, NULL);
    strftime(date, 32, "%Y%m%d%H%M%S", localtime(&tv.tv_sec));
    NSSavePanel*    panel = [NSSavePanel savePanel];
    [panel setNameFieldStringValue:[NSString stringWithFormat:@"%s.mp4", date]];
    [panel setMessage:@"Choose path to save record file"];
    [panel setExtensionHidden:YES];
    [panel setCanCreateDirectories:YES];
    [panel beginSheetModalForWindow:self.view.window completionHandler:^(NSInteger result){
        if (result == NSFileHandlingPanelOKButton) {
            NSString *filePath = [[panel URL] path];
            
            if (self.captureView1 && self.captureView2) {
//                NSString *fileName = [filePath lastPathComponent];
//                NSString *path = [filePath substringToIndex:[filePath rangeOfString:fileName].location];
                NSError *error = nil;
                NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@".mp4" options:0 error:&error];
                NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:filePath options:0 range:NSMakeRange(0, filePath.length)];
                if (matches && [matches count] >= 1) {
                    NSRange range = matches.lastObject.range;
                    NSString *name = [filePath substringToIndex:range.location];
                    [self.captureView1 startRecord:[NSString stringWithFormat:@"%@_1.mp4",name]];
                    [self.captureView2 startRecord:[NSString stringWithFormat:@"%@_2.mp4",name]];
                }
                
                
            } else if (self.captureView1) {
                [self.captureView1 startRecord:filePath];
            }
            if (self.captureView2) {
            }
            [self relaodRecordMenu];
        }
    }];
}

- (void)stopRecord {
    if (self.captureView1) {
        [self.captureView1 stopRecord];
    }
    if (self.captureView2) {
        [self.captureView2 stopRecord];
    }
    [self relaodRecordMenu];
}

- (void)viewDidLoad {
    [self.view setWantsLayer:YES];
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    APITest *test = [[APITest alloc] init];
//    [test testCaptureAPI];
//    [test testProCaptureAPI];
//    [test testUSBCaptureAPI];
//    return;
    
    self.constraintList = [[NSMutableArray alloc] init];
    //base UI
    MWCaptureInitInstance();
    MWRefreshDevice();
    
    NSMenu *mainMenu = [NSApp mainMenu];
    
    NSMenuItem *mainMenuFileItem = [[NSMenuItem alloc] init];
    [mainMenu addItem:mainMenuFileItem];
    NSMenu *fileMenu = [[NSMenu alloc] initWithTitle:@"File"];
    [mainMenuFileItem setSubmenu:fileMenu];
    [fileMenu setAutoenablesItems:NO];
    self.startRecordItem = [fileMenu addItemWithTitle:@"Start record" action:@selector(startRecord:) keyEquivalent:@""];
    self.stopRecordItem = [fileMenu addItemWithTitle:@"Stop record" action:@selector(stopRecord) keyEquivalent:@""];
    
    NSMenuItem *lineControlItem = [[NSMenuItem alloc] init];
    [mainMenu addItem:lineControlItem];
    self.lineMenu = [[NSMenu alloc] initWithTitle:@"Line"];
    [lineControlItem setSubmenu:self.lineMenu];
    
    NSMenuItem *signalItem = [self.lineMenu addItemWithTitle:@"Signal" action:@selector(singleCapture:) keyEquivalent:@""];
    [signalItem setTag:0];
    
    NSMenuItem *multiItem = [self.lineMenu addItemWithTitle:@"Multi" action:@selector(multiCapture:) keyEquivalent:@""];
    [multiItem setTag:1];
    
    [self singleCapture:signalItem];

    self.view.window.delegate = self;
}

- (BOOL)windowShouldClose:(NSWindow *)sender {
    
    [self stopLine2];
    [self stopLine1];
    
    return YES;
}

- (void)viewDidDisappear {
    [self stopLine2];
    [self stopLine1];
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}

- (void)multiCapture:(NSMenuItem *)item
{
    NSMenuItem * selectedItem;
    if (@available(macOS 14.0, *)) {
        if (self.lineMenu.selectedItems.count > 0) {
            selectedItem = self.lineMenu.selectedItems.firstObject;
        }
    } else {
        // Fallback on earlier versions
    }
    if (selectedItem == item) {
        return;
    }
    if (selectedItem) {
        [selectedItem setState:NSControlStateValueOff];
        [item setState:NSControlStateValueOn];
        //启动第二路采集
        [self startLine2];
    }
}

- (void)singleCapture:(NSMenuItem *)item
{
    NSMenuItem * selectedItem;
    if (@available(macOS 14.0, *)) {
        if (self.lineMenu.selectedItems.count > 0) {
            selectedItem = self.lineMenu.selectedItems.firstObject;
        }
    } else {
        // Fallback on earlier versions
    }
    if (selectedItem == item) {
        return;
    }
    if (selectedItem) {
        [selectedItem setState:NSControlStateValueOff];
        [item setState:NSControlStateValueOn];
        //停止第二路采集
        [self stopLine2];
    } else {
        [item setState:NSControlStateValueOn];
        //启动第一路采集
        [self startLine1];
    }
}

- (void)startLine1
{
    self.captureView1 = [[MWCaptureView alloc] initWithFrame:self.view.frame lineNumber:1];
    [self.view addSubview:self.captureView1];
    self.captureView1.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
//    self.captureView1.statusLabel = self.statusLabel;
    self.captureView1.layer.backgroundColor = [NSColor redColor].CGColor;
    self.captureView1.translatesAutoresizingMaskIntoConstraints = NO;
    self.captureView1.delegate = self;
    
    [self.view removeConstraints:self.constraintList];
    [self.constraintList removeAllObjects];
    
    NSLayoutConstraint *constraintWidth = [NSLayoutConstraint constraintWithItem:self.captureView1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1 constant:0];
    [self.view addConstraint:constraintWidth];
    [self.constraintList addObject:constraintWidth];
    
    NSLayoutConstraint *constraintHeight = [NSLayoutConstraint constraintWithItem:self.captureView1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
    [self.view addConstraint:constraintHeight];
    [self.constraintList addObject:constraintHeight];
    [self relaodRecordMenu];
}

- (void)stopLine1
{
    if (self.captureView1) {
        [self.captureView1 destory];
        [self.captureView1 removeFromSuperview];
        self.captureView1 = nil;
    }
    [self relaodRecordMenu];
}

- (void)startLine2
{
    if (self.captureView1) {
        self.captureView1.frame = CGRectMake(0, 0, self.view.frame.size.width/2.0, self.view.frame.size.height);
//        self.captureView1.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;

    }
    
    self.captureView2 = [[MWCaptureView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2.0, 0, self.view.frame.size.width/2.0, self.view.frame.size.height) lineNumber:2];
    [self.view addSubview:self.captureView2];
//    self.captureView2.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
//    self.captureView2.statusLabel = self.statusLabel;
    self.captureView2.layer.backgroundColor = [NSColor yellowColor].CGColor;
    self.captureView2.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view removeConstraints:self.constraintList];
    [self.constraintList removeAllObjects];
    self.captureView2.delegate = self;

    // 假设self.view是父视图，view1和view2是子视图
    NSLayoutConstraint *constraintWidth = [NSLayoutConstraint constraintWithItem:self.captureView1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0];
    [self.view addConstraint:constraintWidth];
    [self.constraintList addObject:constraintWidth];
    
    NSLayoutConstraint *constraintHeight = [NSLayoutConstraint constraintWithItem:self.captureView1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
    [self.view addConstraint:constraintHeight];
    [self.constraintList addObject:constraintHeight];

     
    NSLayoutConstraint *constraintRight = [NSLayoutConstraint constraintWithItem:self.captureView2 attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.captureView1 attribute:NSLayoutAttributeTrailing multiplier:1 constant:0];
    [self.view addConstraint:constraintRight];
    [self.constraintList addObject:constraintRight];

    NSLayoutConstraint *constraintWidth2 = [NSLayoutConstraint constraintWithItem:self.captureView2 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0];
    [self.view addConstraint:constraintWidth2];
    [self.constraintList addObject:constraintWidth2];
    
    NSLayoutConstraint *constraintHeight2 = [NSLayoutConstraint constraintWithItem:self.captureView2 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
    [self.view addConstraint:constraintHeight2];
    [self.constraintList addObject:constraintHeight2];

}

- (void)stopLine2
{
    NSMenu *mainMenu = [NSApp mainMenu];
    int count = (int)mainMenu.itemArray.count;
    if (count >= 4) {
        [mainMenu removeItemAtIndex:count-1];
        [mainMenu removeItemAtIndex:count-2];
        [mainMenu removeItemAtIndex:count-3];
        [mainMenu removeItemAtIndex:count-4];
    }
    
    if (self.captureView2) {
        [self.captureView2 destory];
        [self.captureView2 removeFromSuperview];
        self.captureView2 = nil;
    }
    if (self.captureView1) {
        self.captureView1.frame = self.view.frame;
//        self.captureView1.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
    }
    
    if (self.constraintList) {
        [self.view removeConstraints:self.constraintList];
        [self.constraintList removeAllObjects];
        
        NSLayoutConstraint *constraintWidth = [NSLayoutConstraint constraintWithItem:self.captureView1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1 constant:0];
        [self.view addConstraint:constraintWidth];
        [self.constraintList addObject:constraintWidth];
        
        NSLayoutConstraint *constraintHeight = [NSLayoutConstraint constraintWithItem:self.captureView1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
        [self.view addConstraint:constraintHeight];
        [self.constraintList addObject:constraintHeight];
    }
}
#pragma mark - MWCaptureViewDelegate
- (BOOL)isDeviceInUse:(NSString*)devicePath
{
    if (self.captureView1 && [devicePath isEqualToString:self.captureView1.inUseDevicePath]) {
        return YES;
    }
    if (self.captureView2 && [devicePath isEqualToString:self.captureView2.inUseDevicePath]) {
        return YES;
    }
    return NO;
}
@end
