import {Component, Input, OnChanges, SimpleChanges} from '@angular/core';
import {User} from '../../../auth/models/user';
import {Drivers} from '../../../shared/api/endpoints/models/drivers';
import {GeneralInfo} from '../../../shared/api/endpoints/models/general-info';
import {Lastpos} from '../../../shared/api/endpoints/models/lastpos';
import {Sensor} from '../../../shared/api/endpoints/models/sensor';
import {Unit} from '../../../shared/api/endpoints/models/unit';
import {DataService} from '../../../shared/api/endpoints/services/data.service';
import {SensorsService} from '../../../shared/api/endpoints/services/sensors.service';
import {ConfirmationService, MessageService} from 'primeng/api';
import {ManagementService} from '../../../shared/api/endpoints/services/management.service';
import {ToastService} from '../../../shared/services/toast.service';
import {AuthService} from '../../../auth/services/auth.service';
import {Config} from '../../../shared/api/endpoints/models/config';
import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-custom-dashboard',
  templateUrl: './custom-dashboard.component.html',
  styleUrls: ['./custom-dashboard.component.scss']
})
export class CustomDashboardComponent implements OnChanges {
  @Input('user') loggedUser: User;
  @Input('units') units:
      Array<{ drivers?: Drivers; generalInfo?: GeneralInfo; holder?: any; lastpos?: Lastpos; sensors?: Array<Sensor>; unit?: Unit }>;

  cstmUnits: Array<{ drivers?: Drivers; generalInfo?: GeneralInfo; holder?: any; lastpos?: Lastpos; sensors?: Array<Sensor>; unit?: Unit }>;

  constructor(
      private dataService: DataService,
      private sensorService: SensorsService,
      private confirmationService: ConfirmationService,
      private messageService: MessageService,
      private managementService: ManagementService,
      private toastService: ToastService,
      private authService: AuthService,
      private http: HttpClient
  ) {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.units && changes.units.currentValue) {
      console.log('New units data arrived in child.');
      // Once data is here, process
      this.createGraphs();
    }
  }

  /**
   * Get all units and theirs sensors from backend
   */
  createGraphs() {
    this.http.get<Config>('assets/example.json').subscribe(config => {

      // 1. Store and sort the raw master data
      this.units.forEach(u => u.sensors?.sort((a, b) => (a.sensorId ?? 0) - (b.sensorId ?? 0)));

      // 2. Extract configuration selections
      const {units: unitSelections, globalSensors} = config.preferences.selections;

      // 3. Perform the filtering logic
      this.cstmUnits = this.units.map(masterUnit => {

        // Find specific config for this unit
        const selection = unitSelections.find(u => u.unitId === masterUnit.unit?.unitId);

        const filteredSensors = (masterUnit.sensors || []).filter(sensor => {
          const sId = sensor.sensorId;
          if (sId === undefined) return false;

          const isGlobal = globalSensors.includes(sId);
          let isLocallySelected = false;

          if (selection) {
            isLocallySelected = selection.sensors === 'ALL' ||
                (Array.isArray(selection.sensors) && selection.sensors.includes(sId));
          }

          return isGlobal || isLocallySelected;
        });

        // Return the unit structure with the new filtered sensor array
        return {
          ...masterUnit,
          sensors: filteredSensors
        };
      })
      // 4. Final step: Only keep units that have at least one valid sensor
      .filter(u => u.sensors.length > 0);

      console.log('Filtered cstmUnits:', this.cstmUnits);
    }, err => this.toastService.showError(err.error.message));
  }

  }
