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

@Component({
  selector: 'app-cron-job-builder',
  templateUrl: './cron-job-builder.component.html',
  styleUrls: ['./cron-job-builder.component.scss']
})
export class CronJobBuilderComponent implements OnInit, OnChanges {
  @Input() cronExpression: string = '';
  @Input() instanceId: string = ''; // Unique identifier for each instance
  @Output() cronExpressionChange = new EventEmitter<string>();
  
  // Cron job fields
  minute: string = '*';
  hour: string = '*';
  dayOfMonth: string = '*';
  month: string = '*';
  dayOfWeek: string = '*';
  
  // Human readable description
  cronDescription: string = '';
  
  // Options for selectors
  minuteOptions: any[] = [];
  hourOptions: any[] = [];
  dayOfMonthOptions: any[] = [];
  monthOptions: any[] = [];
  dayOfWeekOptions: any[] = [];

  ngOnInit() {
    // Initialize options for each instance
    this.minuteOptions = this.generateOptions(0, 59);
    this.hourOptions = this.generateOptions(0, 23);
    this.dayOfMonthOptions = this.generateOptions(1, 31);
    this.monthOptions = [
      { value: '*', label: 'Every month' },
      { value: '1', label: 'January' },
      { value: '2', label: 'February' },
      { value: '3', label: 'March' },
      { value: '4', label: 'April' },
      { value: '5', label: 'May' },
      { value: '6', label: 'June' },
      { value: '7', label: 'July' },
      { value: '8', label: 'August' },
      { value: '9', label: 'September' },
      { value: '10', label: 'October' },
      { value: '11', label: 'November' },
      { value: '12', label: 'December' }
    ];
    this.dayOfWeekOptions = [
      { value: '*', label: 'Every day' },
      { value: '0', label: 'Sunday' },
      { value: '1', label: 'Monday' },
      { value: '2', label: 'Tuesday' },
      { value: '3', label: 'Wednesday' },
      { value: '4', label: 'Thursday' },
      { value: '5', label: 'Friday' },
      { value: '6', label: 'Saturday' }
    ];
    
    if (this.cronExpression) {
      this.parseCronExpression(this.cronExpression);
    }
    // Generate initial description
    this.generateDescription();
  }
  
  ngOnChanges(changes: SimpleChanges) {
    // When cronExpression input changes, update the component state
    if (changes['cronExpression'] && !changes['cronExpression'].firstChange) {
      this.parseCronExpression(changes['cronExpression'].currentValue);
      this.generateDescription();
    }
  }

  generateOptions(start: number, end: number): any[] {
    const options = [{ value: '*', label: `Every (${start === 0 ? '0' : start}-${end})` }];
    for (let i = start; i <= end; i++) {
      options.push({ value: i.toString(), label: i.toString() });
    }
    return options;
  }

  parseCronExpression(expression: string) {
    const parts = expression.split(' ');
    if (parts.length >= 5) {
      this.minute = parts[0];
      this.hour = parts[1];
      this.dayOfMonth = parts[2];
      this.month = parts[3];
      this.dayOfWeek = parts[4];
    }
  }
  
  generateDescription() {
    let description = 'Runs ';
    
    // Minute description
    if (this.minute === '*') {
      description += 'every minute';
    } else if (this.minute.includes('/')) {
      const interval = this.minute.split('/')[1];
      description += `every ${interval} minutes`;
    } else {
      description += `at minute ${this.minute}`;
    }
    
    // Hour description
    if (this.hour === '*') {
      if (this.minute === '*') {
        description += '';
      } else {
        description += ' past every hour';
      }
    } else if (this.hour.includes('/')) {
      const interval = this.hour.split('/')[1];
      description += ` past every ${interval} hours`;
    } else {
      description += ` past hour ${this.hour}`;
    }
    
    // Day of month description
    if (this.dayOfMonth !== '*' && this.dayOfMonth !== '?') {
      description += ` on day ${this.dayOfMonth}`;
    }
    
    // Month description
    if (this.month !== '*') {
      const monthNames = ['', 'January', 'February', 'March', 'April', 'May', 'June', 
                         'July', 'August', 'September', 'October', 'November', 'December'];
      if (this.month.match(/^\d+$/)) {
        description += ` in ${monthNames[parseInt(this.month)]}`;
      } else {
        description += ` in ${this.month}`;
      }
    }
    
    // Day of week description
    if (this.dayOfWeek !== '*' && this.dayOfWeek !== '?') {
      const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
      if (this.dayOfWeek.match(/^\d+$/)) {
        description += ` on ${dayNames[parseInt(this.dayOfWeek)]}`;
      } else {
        description += ` on ${this.dayOfWeek}`;
      }
    }
    
    // Special case for simple patterns
    if (this.minute === '0' && this.hour === '0' && this.dayOfMonth === '1' && this.month === '*' && this.dayOfWeek === '*') {
      description = 'Runs at midnight on the first day of every month';
    } else if (this.minute === '0' && this.hour === '0' && this.dayOfMonth === '*' && this.month === '*' && this.dayOfWeek === '*') {
      description = 'Runs at midnight every day';
    } else if (this.minute === '0' && this.hour === '*' && this.dayOfMonth === '*' && this.month === '*' && this.dayOfWeek === '*') {
      description = 'Runs at the top of every hour';
    } else if (this.minute === '*' && this.hour === '*' && this.dayOfMonth === '*' && this.month === '*' && this.dayOfWeek === '*') {
      description = 'Runs every minute';
    }
    
    this.cronDescription = description;
  }

  buildCronExpression() {
    const expression = `${this.minute} ${this.hour} ${this.dayOfMonth} ${this.month} ${this.dayOfWeek}`;
    this.cronExpressionChange.emit(expression);
    this.generateDescription(); // Update description when expression changes
    return expression;
  }

  onFieldChange() {
    this.buildCronExpression();
  }
}