import { Subject, of } from 'rxjs';

import {
  Component,
  OnInit,
  OnDestroy,
  ChangeDetectionStrategy,
  Inject
} from '@angular/core';

import { Store } from '@ngrx/store';

import {
  MatDialogRef,
  MAT_DIALOG_DATA,
  MatDialog,
  MatDialogConfig
} from '@angular/material/dialog';

import { I18nService } from '@ucap/ng-i18n';

import {
  AlertDialogComponent,
  AlertDialogData,
  AlertDialogResult
} from '@ucap/ng-ui';
import { take, map, catchError } from 'rxjs/operators';

export interface EditInlineInputDialogData {
  title: string;
  curValue?: string;
  placeholder: string;
  left?: number;
  top?: number;
}
export interface EditInlineInputDialogResult {
  choice: boolean;
  curValue?: string;
}

@Component({
  selector: 'app-dialog-group-edit-inline-input',
  templateUrl: './edit-inline-input.dialog.component.html',
  styleUrls: ['./edit-inline-input.dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class EditInlineInputDialogComponent implements OnInit, OnDestroy {
  constructor(
    public dialogRef: MatDialogRef<
      EditInlineInputDialogData,
      EditInlineInputDialogResult
    >,
    @Inject(MAT_DIALOG_DATA) public data: EditInlineInputDialogData,

    private store: Store<any>,
    private i18nService: I18nService,
    public dialog: MatDialog
  ) {}

  private ngOnDestroySubject: Subject<void>;

  ngOnInit(): void {
    const matDialogConfig: MatDialogConfig = new MatDialogConfig();

    matDialogConfig.position = {
      left: `${this.data.left}px`,
      top: `${this.data.top}px`
    };

    this.dialogRef.updatePosition(matDialogConfig.position);

    this.ngOnDestroySubject = new Subject();
  }

  ngOnDestroy(): void {
    if (!!this.ngOnDestroySubject) {
      this.ngOnDestroySubject.complete();
    }
  }

  onClosed(event: MouseEvent): void {
    this.doAction(false);
  }

  onApply(inputValue: string) {
    this.doAction(true, inputValue);
  }

  doAction(choice: boolean, curValue?: string): void {
    if (!choice) {
      this.dialogRef.close({ choice: false });
    }

    if (curValue.localeCompare('') === 0) {
      const dialogRef = this.dialog.open<
        AlertDialogComponent,
        AlertDialogData,
        AlertDialogResult
      >(AlertDialogComponent, {
        data: {
          title: this.i18nService.t('moreMenu.error.label'),
          html: this.i18nService.t('moreMenu.error.requireName')
        }
      });
      dialogRef
        .afterClosed()
        .pipe(
          take(1),
          map((result) => {}),
          catchError((err) => {
            return of(err);
          })
        )
        .subscribe();
      return;
    }

    this.dialogRef.close({ choice, curValue });
  }
}
