import {
  Component,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges
} from '@angular/core'
import { DSMeta } from 'src/app/models/sas/editors-getdata.model'
import { DSMetaGroupped } from './models/dsmeta-groupped.model'

@Component({
  selector: 'app-dataset-info',
  templateUrl: './dataset-info.component.html',
  styleUrls: ['./dataset-info.component.scss']
})
export class DatasetInfoComponent implements OnInit, OnChanges {
  @Input() open: boolean = false
  @Input() dsmeta: DSMeta[] = []

  @Output() openChange = new EventEmitter<boolean>()

  dsmetaGroupped: DSMetaGroupped[] = []

  constructor() {}

  ngOnInit(): void {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.dsmeta?.currentValue?.length > 0) {
      this.parseDSMeta()
    }
  }

  parseDSMeta() {
    this.dsmetaGroupped = []

    for (let info of this.dsmeta) {
      let groupIndex = this.dsmetaGroupped.findIndex(
        (x) => x.group === info.ODS_TABLE
      )

      if (groupIndex < 0)
        groupIndex =
          this.dsmetaGroupped.push({
            group: info.ODS_TABLE,
            dsmeta: []
          }) - 1

      this.dsmetaGroupped[groupIndex].dsmeta.push(info)
    }
  }

  onOpenChange(open: boolean) {
    this.open = open
    this.openChange.emit(open)
  }

  onCloseClick() {
    this.onOpenChange(false)
  }
}
