import { Component, ViewChild, OnInit, OnDestroy } from '@angular/core';
import { GraphComponent } from '../graph/graph.component';
import { CommonModule } from '@angular/common';
import { ChangeDetectorRef } from '@angular/core';

@Component({
    selector: 'app-historygraph',
    standalone: true,
    imports: [GraphComponent, CommonModule],
    templateUrl: './historygraph.component.html',
    styleUrls: ['./historygraph.component.scss']
})
export class HistorygraphComponent implements OnInit, OnDestroy {
    selectedButton: string = '';
    selectedInterval: string = '';
    intervalId: any;
    greeting: string = '';

    constructor(private cdr: ChangeDetectorRef) {}

    @ViewChild(GraphComponent) graphComponent!: GraphComponent;  

    ngOnInit(): void {
        this.updateGreeting();
        this.selectedButton = 'hourly';
        this.selectedInterval = 'HOURLY';  
    }
    

    private debounceTimeout: any;

    updateInterval(interval: string): void {
        clearTimeout(this.debounceTimeout);
        this.debounceTimeout = setTimeout(() => {
            if (this.selectedInterval !== interval) {
                this.selectedInterval = interval;  
                this.selectedButton = interval.toLowerCase();  
                this.cdr.detectChanges();
                this.graphComponent.updateCharts();
            }
        }, 300);
    }

    ngOnDestroy(): void {
        if (this.intervalId) {
            clearInterval(this.intervalId);
        }
    }

    updateGreeting(): void {
        const hour = new Date().getHours();
        if (hour < 12) {
            this.greeting = 'Good Morning';
        } else if (hour < 18) {
            this.greeting = 'Good Afternoon';
        } else {
            this.greeting = 'Good Evening';
        }
    }
}

