import {
  ChangeDetectorRef,
  Component,
  Inject,
  OnInit,
  ViewEncapsulation,
} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { SiteService } from 'app/modules/polyglot/domain/services/site.service';
import { IdentityService } from 'app/modules/polyglot/member/services/identity.service';
import { Site } from 'app/modules/protobuf/models/domain/site_pb';
import { MemberModel } from 'app/modules/protobuf/models/member/member_pb';

export interface RegistComposeData {
  title: string;
  parent: MemberModel;
  sites: Site[];
}
export interface RegistComposeResult {
  parentId: string;
  siteName: string;
  signinId: string;
  password: string;
  exchangePassword: string;
  nickname: string;
  calculateType: string;
  phoneNumber: string;
  bankName: string;
  accountNumber: string;
  accountHolder: string;
}

@Component({
  selector: 'app-regist-compose',
  templateUrl: './regist-compose.component.html',
  encapsulation: ViewEncapsulation.None,
})
export class RegistComposeComponent implements OnInit {
  composeForm!: FormGroup;
  sites: any[] = [];
  // quillModules: any = {
  //   toolbar: [
  //     ['bold', 'italic', 'underline'],
  //     [{ align: [] }, { list: 'ordered' }, { list: 'bullet' }],
  //     ['clean'],
  //   ],
  // };

  /**
   * Constructor
   */
  constructor(
    public matDialogRef: MatDialogRef<RegistComposeComponent>,
    @Inject(MAT_DIALOG_DATA) public data: RegistComposeData,
    private _formBuilder: FormBuilder,
    private _identityService: IdentityService,
    private _changeDetectorRef: ChangeDetectorRef
  ) {
    this.data.sites.forEach((v) => console.log(v.getUrl()));
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Lifecycle hooks
  // -----------------------------------------------------------------------------------------------------

  /**
   * On init
   */
  ngOnInit(): void {
    // Create the form
    this.composeForm = this._formBuilder.group({
      partnerId: [{ value: this.data.parent.getUsername(), disabled: true }],
      siteName: ['', [Validators.required]],
      signinId: ['', [Validators.required]],
      password: ['', [Validators.required]],
      exchangePw: ['', [Validators.required]],
      nickname: ['', [Validators.required]],
      calculateType: ['', [Validators.required]],
      phoneNumber: ['', [Validators.required]],
      bankName: ['', [Validators.required]],
      accountNumber: ['', [Validators.required]],
      accountHolder: ['', [Validators.required]],
    });
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Save and close
   */
  saveAndClose(): void {
    // Save the message as a draft
    this.saveAsDraft();

    // Close the dialog
    this.matDialogRef.close();
  }

  /**
   * Discard the message
   */
  discard(): void {}

  /**
   * Save the message as a draft
   */
  saveAsDraft(): void {}

  /**
   * Send the message
   */
  send(): void {
    console.log(this.composeForm.value);
  }

  __checkSigninId(event: FocusEvent): void {
    const signinId = this.composeForm.get('signinId')?.value;
    // console.log(event, '::', signinId);
    this._identityService
      .checkUsernameForDuplication(signinId)
      .then((isUse: boolean) => {
        if (!!isUse) {
          this.composeForm
            .get('signinId')
            ?.setErrors({ signinIdDuplicate: true });
        }
        // this._changeDetectorRef.markForCheck();
      });
  }

  __checkNickname(event: FocusEvent): void {
    const nickname = this.composeForm.get('nickname')?.value;

    this._identityService
      .checkNicknameForDuplication(nickname)
      .then((isUse: boolean) => {
        if (!!isUse) {
          this.composeForm
            .get('nickname')
            ?.setErrors({ nicknameDuplicate: true });
        }
        // this._changeDetectorRef.markForCheck();
      });
  }
}
