import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { ContentService } from './content.service';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { FormBuilder, Form, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-category-add-lang-modal',
  template: `

<form [formGroup]="form" autocomplete="off" (ngSubmit)="onSubmit()" novalidate class="form-horizontal ">
  <div class="modal-header">
    <h4 class="modal-title">{{title}}</h4>
    <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">

    <div class="alert alert-danger" *ngIf="globalError">{{globalError}}</div>
    <div class="alert alert-success" *ngIf="globalSuccess">{{globalSuccess}}</div>


    <div class="form-group">
      <label i18n>编码</label>
      <input type="text" formControlName="code" class="form-control"
        [ngClass]="{ 'is-invalid': showErrors && f['code'].errors, 'is-valid' : f['code'].valid }" />
      <div *ngIf="showErrors && f['code'].errors" class="invalid-feedback">
        <div *ngIf="f['code'].errors['required']" i18n>请输入语言编码</div>
      </div>
    </div>

    <div class="form-group">
      <label i18n>名称</label>
      <input type="text" formControlName="name" class="form-control"
        [ngClass]="{ 'is-invalid': showErrors && f['name'].errors, 'is-valid' : f['name'].valid }" />
      <div *ngIf="showErrors && f['name'].errors" class="invalid-feedback">
        <div *ngIf="f['name'].errors['required']" i18n>请输入语言名称</div>
      </div>
    </div>


    <p>{{form.value|json}}</p>

  </div>
  <div class="modal-footer">
    <button type="submit" [disabled]="submitting" class="btn btn-outline-success" i18n>添加</button>
  </div>
</form>
  `,
  styles: [`

    `]
})
export class CategoryAddLangModalComponent implements OnInit {

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

  form: FormGroup;
  title = '添加语言';
  showErrors = false;
  globalError = null;
  submitting = false;
  globalSuccess = null;

  constructor(
    private contentService: ContentService,
    public activeModal: NgbActiveModal,
    private fb: FormBuilder,
  ) { }

  ngOnInit() {
    this.form = this.fb.group({
      code: [null, [Validators.required]],
      name: [null, [Validators.required]],
    })
  }

  onSubmit() {
    if (this.form.invalid) {
      this.showErrors = true;
      return;
    }
    this.showErrors = false;
    this.submitting = true;
    this.contentService.langAdd(this.form.value).toPromise()
      .then(res => {
        this.activeModal.close('success');
        this.updates.emit('update');
      })
      .catch(err => {
        this.globalError = err.error.msg;
      }).then(() => {
        this.submitting = false;
      })
  }

  get f() {
    return this.form.controls;
  }
}
