//
//  basicTabViewController.m
//  LEDArray
//
//  Created by Brian Burley on 2026-01-15.
//

#import "basicTabViewController.h"

@interface basicTabViewController ()

@end

@implementation basicTabViewController

- (NSInteger)startAddress {
    return [_startAddressField integerValue];
}

- (NSInteger)endAddress {
    return [_endAddressField integerValue];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.colorBox.wantsLayer = YES; // Enable CALayer so we can set background color
    self.colorBox.layer.backgroundColor = [[NSColor whiteColor] CGColor]; // initial color
    
    // Enable user interaction
    [self.colorBox setAllowsCutCopyPaste:NO];
    [self.colorBox setImageScaling:NSImageScaleAxesIndependently];
    
    // Add click gesture
    NSClickGestureRecognizer *clickGesture = [[NSClickGestureRecognizer alloc] initWithTarget:self action:@selector(colorBoxClicked:)];
    [self.colorBox addGestureRecognizer:clickGesture];
}

- (void)viewWillAppear {
    [super viewWillAppear];
    NSSize size = NSMakeSize(538, 625);
    [self.resizeDelegate tabDidRequestResize:size];
}


- (IBAction)stepperChanged:(NSStepper *)sender {
    if (sender == self.startUpDown) {
        self.startAddressField.integerValue = sender.integerValue;
    } else if (sender == self.endUpDown) {
        self.endAddressField.integerValue = sender.integerValue;
    }
}

- (void)colorBoxClicked:(NSClickGestureRecognizer *)sender {
    NSColorPanel *colorPanel = [NSColorPanel sharedColorPanel];
    [colorPanel setTarget:self];
    [colorPanel setAction:@selector(colorPicked:)];
    [colorPanel makeKeyAndOrderFront:nil];
}

- (void)colorPicked:(NSColorPanel *)sender {
    NSColor *selectedColor = [sender color];
    
    // Update the colorBox
    self.colorBox.layer.backgroundColor = [selectedColor CGColor];
    
    // Update the label with hex code
    NSString *hexString = [self hexStringFromColor:selectedColor];
    self.colorHexBox.stringValue = hexString; // assume you have an IBOutlet called hexLabel
    
    // Send back to main view controller via delegate
    if ([self.delegate respondsToSelector:
         @selector(basicTabViewController:didSelectColor:integers:)]) {

        [self.delegate basicTabViewController:self
                               didSelectColor:selectedColor
                                     integers:@[
                                         @([_startAddressField integerValue]),
                                         @([_endAddressField integerValue])
                                     ]];
    }
}

- (NSString *)hexStringFromColor:(NSColor *)color {
    NSColor *rgbColor = [color colorUsingColorSpace:[NSColorSpace deviceRGBColorSpace]];
    NSInteger red = rgbColor.redComponent * 255;
    NSInteger green = rgbColor.greenComponent * 255;
    NSInteger blue = rgbColor.blueComponent * 255;
    return [NSString stringWithFormat:@"#%02lX%02lX%02lX", (long)red, (long)green, (long)blue];
}


@end
