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

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

  @Output() openChange = new EventEmitter<boolean>()
  @Output() rowClicked = new EventEmitter<Version | DSMeta>()

  dsmetaTabs: Tab<DSMeta>[] = []
  versionsTabs: Tab<Version>[] = []

  tabs: Tab<DSMeta | Version>[] = []

  constructor() {}

  ngOnInit(): void {}

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

      this.tabs = [...[...this.dsmetaTabs], ...[...this.versionsTabs]]
    }
  }

  parseDSMeta() {
    this.dsmetaTabs = []

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

      if (groupIndex < 0)
        groupIndex =
          this.dsmetaTabs.push({
            name: info.ODS_TABLE,
            title: 'Dataset Meta',
            colsToDisplay: [{ colKey: 'NAME' }, { colKey: 'VALUE' }],
            meta: [],
            onRowClick: (value: DSMeta) => {
              this.rowClicked.emit(value)
            }
          }) - 1

      this.dsmetaTabs[groupIndex].meta.push(info)
    }
  }

  parseVersions() {
    this.versionsTabs = [
      {
        name: 'VERSIONS',
        title: 'Dataset Meta',
        colsToDisplay: [
          { colKey: 'LOAD_REF' },
          { colKey: 'USER_NM' },
          { colKey: 'VERSION_DTTM' },
          { colKey: 'NEW_RECORDS', colName: 'ADD' },
          { colKey: 'CHANGED_RECORDS', colName: 'MOD' },
          { colKey: 'DELETED_RECORDS', colName: 'DEL' },
          { colKey: 'VERSION_DESC' }
        ],
        meta: this.versions,
        onRowClick: (value: Version) => {
          this.rowClicked.emit(value)
        }
      }
    ]
  }

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

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