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

#import "advancedTabViewController.h"

@interface advancedTabViewController ()

@end

@interface advancedTabViewController () <NSTableViewDataSource, NSTableViewDelegate>
@property (nonatomic, strong) NSMutableArray<ledColorEntryRow *> *entries;
@end

@implementation advancedTabViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.entries = [NSMutableArray array];
}

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

- (IBAction)patternAddRowClick:(id)sender {
    ledColorEntryRow *entry = [ledColorEntryRow new];
    entry.ledIndex = self.entries.count;
    entry.color = NSColor.blackColor;

    [self.entries addObject:entry];
    [self.patternBuilderTable reloadData];
    
    NSInteger newRow = self.entries.count - 1;
    [self.patternBuilderTable selectRowIndexes:[NSIndexSet indexSetWithIndex:newRow]
                          byExtendingSelection:NO];
    [self.patternBuilderTable scrollRowToVisible:newRow];
}

- (IBAction)patternRemoveRowClick:(id)sender {
    NSInteger row = self.patternBuilderTable.selectedRow;
        if (row >= 0 && row < self.entries.count) {
            [self.entries removeObjectAtIndex:row];
            [self.patternBuilderTable reloadData];
        }
}
- (IBAction)sendLEDsClick:(id)sender {
    NSInteger start = self.advStarAddr.integerValue;
    NSInteger end   = self.advEndAddress.integerValue;
    NSInteger fade  = self.fadeTimeTxt.integerValue;  // grab fade time
    NSInteger leds  = self.patternBuilderTable.numberOfRows;
    
    
    if ([self.delegate respondsToSelector:@selector(advancedTab:didSendColors:startAddress:endAddress:fadeTime:ledCount:)]) {
        [self.delegate advancedTab:self
                     didSendColors:self.entries
                      startAddress:start
                        endAddress:end
                          fadeTime:fade
                          ledCount:leds];
    }
}

- (IBAction)stepperChanged:(NSStepper *)sender {
    if (sender == self.advStartUpDown) {
        self.advStarAddr.integerValue = sender.integerValue;
    } else if (sender == self.advEndUpDown) {
        self.advEndAddress.integerValue = sender.integerValue;
    }
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return self.entries.count;
}

- (NSView *)tableView:(NSTableView *)patternBuilderTable
   viewForTableColumn:(NSTableColumn *)tableColumn
                  row:(NSInteger)row
{
    ledColorEntryRow *entry = self.entries[row];

    if ([tableColumn.identifier isEqualToString:@"indexColumn"]) {
        NSTableCellView *cell = [patternBuilderTable makeViewWithIdentifier:@"IndexCell" owner:self];
        if (cell.textField) {
            cell.textField.stringValue = [NSString stringWithFormat:@"%ld", (long)entry.ledIndex];
        }
        return cell;
    }

    if ([tableColumn.identifier isEqualToString:@"colorColumn"]) {
        colorCellView *cell = [patternBuilderTable makeViewWithIdentifier:@"ColorCell" owner:self];
        
        ledColorEntryRow *entry = self.entries[row];

        // Set the color of the box
        cell.colorView.wantsLayer = YES;
        cell.colorView.layer.backgroundColor = entry.color.CGColor;

        // Remove old gestures to avoid duplicates
        for (NSGestureRecognizer *g in cell.colorView.gestureRecognizers) {
            [cell.colorView removeGestureRecognizer:g];
        }

        // Add a new click gesture
        NSClickGestureRecognizer *click =
            [[NSClickGestureRecognizer alloc] initWithTarget:self
                                                      action:@selector(colorCellClicked:)];
        [cell.colorView addGestureRecognizer:click];

        // Tag the view with the row so we know which entry is clicked
        cell.colorView.tag = row;

        return cell;
    }

    // Fallback for unexpected columns
    NSTableCellView *cell = [[NSTableCellView alloc] initWithFrame:NSMakeRect(0, 0, tableColumn.width, 20)];
    return cell;
}

- (void)colorCellClicked:(NSClickGestureRecognizer *)sender {
    NSInteger row = sender.view.tag; // now using the tag from the colorBox
    if (row < 0 || row >= self.entries.count) return;

    self.colorPanelRow = row;

    NSColorPanel *panel = [NSColorPanel sharedColorPanel];
    panel.target = self;
    panel.action = @selector(colorPicked:);
    
    NSColor *initialColor = self.entries[row].color;
    if ([initialColor isEqual:[NSColor blackColor]]) {
        initialColor = [NSColor whiteColor];  // default to white if black
    }
    panel.color = initialColor;
    panel.showsAlpha = NO;

    [panel makeKeyAndOrderFront:nil];
}

- (void)colorPicked:(NSColorPanel *)panel {
    NSInteger row = self.colorPanelRow;
    if (row < 0 || row >= self.entries.count) return;

    self.entries[row].color = panel.color;
    [self.patternBuilderTable reloadData];
}

@end

