import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { ContentService } from './content.service';
import { FormBuilder, Form, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormUtils } from 'src/app/lib/utils/form-utils';
import { firstValueFrom } from 'rxjs';

@Component({
  selector: 'app-translate-add',
  template: `

    <p *ngIf="debug">{{form.value|json}}</p>

<form [formGroup]="form" autocomplete="off" (ngSubmit)="onSubmit()" novalidate class="form-horizontal ">
  <nz-form-item>
    <nz-form-control i18n-nzErrorTip nzErrorTip="请输入ID">
      <nz-input-group nzPrefixIcon="user">
        <input nz-input formControlName="tag" placeholder="ID">
      </nz-input-group>
    </nz-form-control>
  </nz-form-item>

  <nz-form-item>
    <nz-form-control i18n-nzErrorTip nzErrorTip="请输入翻译英文名">
      <nz-input-group nzPrefixIcon="user">
        <input nz-input formControlName="en" i18n-placeholder placeholder="英文名">
      </nz-input-group>
    </nz-form-control>
  </nz-form-item>

  <nz-form-item>
    <nz-form-control i18n-nzErrorTip nzErrorTip="请输入翻译中文名">
      <nz-input-group nzPrefixIcon="user">
        <input nz-input formControlName="zh" i18n-placeholder placeholder="中文名">
      </nz-input-group>
    </nz-form-control>
  </nz-form-item>

  <div class="d-flex flex-row-reverse">
    <button nz-button nzType="primary" nzBlock type="submit" [disabled]="isLoading" i18n>添加</button>
  </div>
</form>
  `,
  styles: [`

    `]
})
export class TranslateAddComponent implements OnInit {


  @Output() onSuccess = new EventEmitter<any>();
  @Output() onError = new EventEmitter<any>();
  @Input() debug: boolean = false;

  @Output()
  updates = new EventEmitter<any>();

  form: FormGroup;
  isLoading = false;

  constructor(
    private contentService: ContentService,
    private fb: FormBuilder,
    private message: NzMessageService,
  ) { }

  ngOnInit() {
    this.form = this.fb.group({
      en: [null, [Validators.required]],
      zh: [null, [Validators.required]],
      tag: [null, [Validators.required]],
    })
  }

  onSubmit() {
    if (this.form.invalid) {
      FormUtils.markAsDirty(this.form);
      return;
    }
    this.isLoading = true;
    firstValueFrom(this.contentService.translateAdd(this.form.value))
      .then(res => {
        this.onSuccess.emit(this.form.value);
        this.message.success($localize`添加成功`);
      })
      .catch(err => {
        this.message.error(err.error?.message || err.message);
        this.onError.emit(err);
      }).then(() => {
        this.isLoading = false;
      })
  }


}
