import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-to-do-chart',
  templateUrl: './to-do-chart.component.html',
  styleUrls: ['./to-do-chart.component.scss']
})
export class ToDoChartComponent implements OnInit, OnChanges {
  @Input() xAxis: string;
  @Input() yAxis: string | string[];
  @Input() table: string;
  @Input() datastore: string;
  @Input() charttitle: string;
  @Input() chartlegend: boolean = true;
  @Input() showlabel: boolean = true;
  @Input() chartcolor: boolean;
  @Input() slices: boolean;
  @Input() donut: boolean;
  @Input() charturl: string;
  @Input() chartparameter: string;
  @Input() datasource: string;
  @Input() fieldName: string;
  @Input() connection: number; // Add connection input

  constructor() { }

  ngOnInit(): void {
  }
  
  ngOnChanges(changes: SimpleChanges): void {
    console.log('ToDoChartComponent input changes:', changes);
    
    // Check if any of the key properties have changed
    const xAxisChanged = changes.xAxis && !changes.xAxis.firstChange;
    const yAxisChanged = changes.yAxis && !changes.yAxis.firstChange;
    const tableChanged = changes.table && !changes.table.firstChange;
    const connectionChanged = changes.connection && !changes.connection.firstChange; // Add connection change detection
    
    // Respond to input changes
    if (xAxisChanged || yAxisChanged || tableChanged || connectionChanged) {
      console.log('X or Y axis or table or connection changed, fetching new data');
      // Only fetch data if xAxis, yAxis, table, or connection has changed (and it's not the first change)
      this.fetchToDoData();
    }
  }
  
  data: any;
  todo: string;
  todoList = ['todo 1'];
  
  fetchToDoData(): void {
    // If we have the necessary data, fetch to-do data from the service
    if (this.table) {
      console.log('Fetching to-do data for:', { table: this.table });
      
      // For to-do chart, we might want to fetch data differently
      // This is a placeholder implementation - you may need to adjust based on your API
      console.log('To-do chart would fetch data from table:', this.table);
      
      // In a real implementation, you would connect to your service here
      // For now, we'll just keep the default to-do list
    } else {
      console.log('Missing required data for to-do chart:', { table: this.table });
    }
  }

  public addTodo(todo: string) {
    this.todoList.push(todo);
  }

  public removeTodo(todoIx: number) {
    if (this.todoList.length) {
        this.todoList.splice(todoIx, 1);
    }
  }
}