import {Component, Inject} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import {Dialog} from '../../../../classes/base_components/dialog/dialog';
import {EditComponent} from '../../../../classes/base_components/edit/edit.component';
import {setErrors} from '../../../../classes/utils';
import {Cities, CitiesService} from '../../../../classes/resorcess/cities.service';
import {Universities, UniversitiesService} from '../../../../classes/resorcess/universities.service';
import {Base} from 'ngx-jsonapi/services/base';
import {Units} from '../../../../classes/resorcess/units.service';


@Component({
  selector: 'app-edit-roles',
  templateUrl: './editUnities.component.html',
  styleUrls: ['./editUnities.component.scss']
})

export class EditUnitiesComponent extends EditComponent {
  public loading = false;
  nameCtrl = new FormControl('', [Validators.required]);
  uniCtrl = new FormControl('', [Validators.required]);
  cityCtrl = new FormControl('', [Validators.required]);
  form: FormGroup;
  units: Units;
  universities;
  cities;

  constructor(private fb: FormBuilder,
              public citiesService: CitiesService,
              public universitiesService: UniversitiesService,
              protected  dialog: Dialog,
              public  dialogRef: MatDialogRef<EditUnitiesComponent>,
              @Inject(MAT_DIALOG_DATA)  data,
  ) {
    super();
    this.units = data;
    this.citiesService.register();
    this.universitiesService.register();
    this.form = this.fb.group({
      uniCtrl: this.uniCtrl,
      nameCtrl: this.nameCtrl,
      cityCtrl: this.cityCtrl,
    });
    const basics = JSON.parse(localStorage.getItem('basics'));
    this.universities = Base.newCollection<Universities>();
    (new UniversitiesService()).convert(JSON.parse(basics['universities']), this.universities);
    this.cities = Base.newCollection<Cities>();
    (new CitiesService()).convert(JSON.parse(basics['cities']), this.cities);
    console.log('shahr' , this.cities);
    console.log('uni ' ,  this.universities);
  }

  onSubmit() {
    this.loading = true;
    if (!this.form.valid) {
      this.loading = false;
      return;
    }
    this.units.save({},
      () => {
        this.loading = false;
        this.close();
      },
      (error) => {
        this.loading = false;
        const JsonV = error.errors;
        setErrors(JsonV, this.form.controls, this.dialog);
      });
  }

  close() {
    this.dialogRef.close(true);
  }
}





