import { AfterViewInit, ChangeDetectionStrategy, Component, inject, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { CommonDialogService } from '@core/common-dialog/common-dialog.service';
import { AppSetting } from '@core/domain-classes/app-setting';
import { TranslationService } from '@core/services/translation.service';
import { AppSettingsManageComponent } from '../app-settings-manage/app-settings-manage.component';
import { AppSettingsStore } from '../app-settings-store';
import { FormControl } from '@angular/forms';
import { MatSort } from '@angular/material/sort';
import { tap } from 'rxjs';

@Component({
  selector: 'app-app-settings-list',
  templateUrl: './app-settings-list.component.html',
  styleUrls: ['./app-settings-list.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppSettingsListComponent implements OnInit, AfterViewInit {

  @ViewChild(MatSort) sort: MatSort;
  appSettings: AppSetting[] = [];
  displayedColumns: string[] = ['action', 'name', 'key', 'value'];
  isLoadingResults = true;
  private dialog = inject(MatDialog);
  private commonDialogService = inject(CommonDialogService);
  private translationService = inject(TranslationService);
  public appSettingsStore = inject(AppSettingsStore);
  nameFilterCtl = new FormControl('');
  keyFilterCtl = new FormControl('');
  valueFilterCtl = new FormControl('');

  ngOnInit(): void {
    
    this.nameFilterCtl.valueChanges.subscribe((value) => {
      this.onSortFilterData();
    });
    this.keyFilterCtl.valueChanges.subscribe((value) => {
      this.onSortFilterData();
    });
    this.valueFilterCtl.valueChanges.subscribe((value) => {
      this.onSortFilterData();
    });
  }
  ngAfterViewInit(): void {
    this.sort.sortChange
      .subscribe(() => {
        this.onSortFilterData();
      });
  }

  onSortFilterData(): void {
    this.appSettingsStore.sortFilterAppsettings(this.sort.direction, this.sort.active ?? 'name', this.keyFilterCtl.value, this.valueFilterCtl.value, this.nameFilterCtl.value);
  }

  deleteAppSetting(appSetting: AppSetting) {
    this.commonDialogService
      .deleteConformationDialog(`${this.translationService.getValue('ARE_YOU_SURE_YOU_WANT_TO_DELETE')} ${appSetting.key}`)
      .subscribe((flag: boolean) => {
        if (flag) {
          this.appSettingsStore.deleteAppSettingsById(appSetting.id);
        }
      });
  }


  onManageAppSetting(appSetting?: AppSetting): void {
    const dialogRef = this.dialog.open(AppSettingsManageComponent, {
      width: '350px',
      data: appSetting ? Object.assign({}, appSetting) : null
    });
    dialogRef.afterClosed()
      .subscribe(result => {
      });
  }

}
