import { ChangeDetectionStrategy, Component, HostListener, Inject, Input, OnInit } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Package } from 'src/app/api/models/package';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'app-package-dialog',
  templateUrl: './package-dialog.component.html',
  styleUrls: ['./package-dialog.component.scss']
})
export class PackageDialogComponent implements OnInit {

  packageForm: UntypedFormGroup = new UntypedFormGroup({});

  constructor(@Inject(MAT_DIALOG_DATA) public data: {
    pkg: Package,
    title: string,
  },
    private mdDialogRef: MatDialogRef<PackageDialogComponent>,
    private formBuilder: UntypedFormBuilder,
  ) {
    if (!data.pkg) {
      data.pkg = {
        name: '',
        url: '',
      }
    }
  }

  ngOnInit(): void {
    this.packageForm = this.formBuilder.group({
      name: [{ value: this.data.pkg.name, disabled: false },
      Validators.required,
      ],
      url: [{ value: this.data.pkg.url, disabled: false },
      Validators.compose([
        Validators.required,
        Validators.pattern("(^(http[s]?:\/\/(.*)$))?"),
      ]),
      ],
      description: [{ value: this.data.pkg.description, disabled: false },
      Validators.compose([
        Validators.required,
        Validators.minLength(4),
      ]),
      ],
    });
  }

  public cancel() {
    this.mdDialogRef.close();
  }

  public submit(value: any) {
    this.mdDialogRef.close(value);
  }

  @HostListener("keydown.esc")
  public onEsc() {
    this.cancel();
  }
}
