import { Component, OnInit, Inject } from '@angular/core';
import {
  FormGroup,
  FormBuilder,
  Validators,
  ValidatorFn,
  AbstractControl
} from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { GroupDetailData } from '@ucap-webmessenger/protocol-sync';

export interface EditGroupDialogData {
  title: string;
  group: GroupDetailData;
}

export interface EditGroupDialogResult {
  choice: boolean;
  groupName: string;
  group: GroupDetailData;
}

@Component({
  selector: 'app-layout-messenger-edit-group',
  templateUrl: './edit-group.dialog.component.html',
  styleUrls: ['./edit-group.dialog.component.scss']
})
export class EditGroupDialogComponent implements OnInit {
  groupName: string;
  inputForm: FormGroup;

  constructor(
    public dialogRef: MatDialogRef<EditGroupDialogData, EditGroupDialogResult>,
    @Inject(MAT_DIALOG_DATA) public data: EditGroupDialogData,
    private formBuilder: FormBuilder
  ) {}

  ngOnInit(): void {
    this.inputForm = this.formBuilder.group({
      groupName: [
        this.data.group.name,
        [Validators.required, this.checkSpecialCharacter()]
      ]
    });
  }

  checkSpecialCharacter(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      const forbidden = /[\{\}\[\]\/?.;:|\)*~`!^+<>@\#$%&\\\=\(\'\"]/g.test(
        control.value
      );
      return forbidden ? { groupName: { value: control.value } } : null;
    };
  }

  onClickChoice(choice: boolean): void {
    this.dialogRef.close({
      choice,
      groupName: this.inputForm.get('groupName').value,
      group: this.data.group
    });
  }
}
