import {Component, Inject, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms';
import {Requests, RequestsService} from '../../../classes/resorcess/requests.service';
import {Dialog} from '../../../classes/base_components/dialog/dialog';
import {environment} from '../../../../environments/environment';
import {HttpClient, HttpEventType} from '@angular/common/http';
import {Lightbox} from 'ngx-lightbox';
import {Type, TypesService} from '../../../classes/resorcess/types.service';
import {Base} from 'ngx-jsonapi/services/base';
import {Universities, UniversitiesService} from '../../../classes/resorcess/universities.service';
import {Cities, CitiesService} from '../../../classes/resorcess/cities.service';
import {Units, UnitsService} from '../../../classes/resorcess/units.service';

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

export class RequestregisterComponent implements OnInit {
  formatFilter = '.jpg, .png, .jpeg|image/*';
  public loading = false;
  nameCtrl = new FormControl();
  last_nameCtrl = new FormControl();
  identify_idCtrl = new FormControl();
  student_codeCtrl = new FormControl();
  birth_dateCtrl = new FormControl();
  addressCtrl = new FormControl();
  birth_certificate_idCtrl = new FormControl();
  father_nameCtrl = new FormControl();
  mobileCtrl = new FormControl();
  phoneCtrl = new FormControl();
  genderCtrl = new FormControl();
  statusCtrl = new FormControl();
  typesCtrl = new FormControl();
  uniCtrl = new FormControl();
  form: FormGroup;
  request: Requests;
  progressbar = [0, 0];
  selectedfile: File = null;
  types;
  universities;
  cities;
  unitsArray;
  units;

  constructor(private fb: FormBuilder,
              public requestService: RequestsService,
              public typeService: TypesService,
              public uniService: UniversitiesService,
              public unitsService: UnitsService,
              public cityService: CitiesService,
              protected  dialog: Dialog,
              private _lightbox: Lightbox,
              private http: HttpClient,
  ) {
    this.request = requestService.new();
    this.unitsArray = [];
    this.typeService.register();
    this.uniService.register();
    this.cityService.register();
    this.unitsService.register();
    this.form = this.fb.group({
      nameCtrl: this.nameCtrl,
      last_nameCtrl: this.last_nameCtrl,
      identify_idCtrl: this.identify_idCtrl,
      student_codeCtrl: this.student_codeCtrl,
      birth_dateCtrl: this.birth_dateCtrl,
      addressCtrl: this.addressCtrl,
      birth_certificate_idCtrl: this.birth_certificate_idCtrl,
      father_nameCtrl: this.father_nameCtrl,
      mobileCtrl: this.mobileCtrl,
      phoneCtrl: this.phoneCtrl,
      genderCtrl: this.genderCtrl,
      statusCtrl: this.statusCtrl,
      typesCtrl: this.typesCtrl,
      uniCtrl: this.uniCtrl,
    });

    const basics = JSON.parse(localStorage.getItem('basics'));
    this.units = Base.newCollection<Units>();
    (new UnitsService()).convert(JSON.parse(basics['units']), this.units);
    this.types = Base.newCollection<Type>();
    (new TypesService()).convert(JSON.parse(basics['types']), this.types);
    this.universities = Base.newCollection<Universities>();
    (new UniversitiesService()).convert(JSON.parse(basics['universities']), this.universities);
    this.cities = Base.newCollection<Cities>();
    (new UniversitiesService()).convert(JSON.parse(basics['cities']), this.cities);
    this.unitsArray = Object.values(this.universities);
  }

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

  ngOnInit() {
  }

  onselect(event, index, hidden_element_id) {
    this.selectedfile = event.target.files[0];
    this.uploade(index, hidden_element_id);
  }

  uploade(index, hidden_element_id) {
    const fd = new FormData();
    fd.append('image', this.selectedfile, this.selectedfile.name);
    this.http.post(environment.app_url + 'docs/upload', fd, {
      reportProgress: true,
      observe: 'events',
    })
      .subscribe(event => {
        if (event.type === HttpEventType.UploadProgress) {
          let percent = Math.round(event.loaded / event.total * 100);
          percent = Math.round(event.loaded / event.total * 100);
          this.progressbar[index] = percent;
        } else if (event.type === HttpEventType.Response) {
          const img_id = event.body['id'];
          const imag_url = event.body['url'];
          this.request[hidden_element_id]['url'] = imag_url;
          this.request[hidden_element_id]['id'] = img_id;
          const element = document.getElementById(hidden_element_id);
          element['value'] = img_id;
          // dispatchEvent be yaro mige ke taghir kard
          element.dispatchEvent(new Event('input'));
        }
      }, error => {
        console.log(error);
      });
  }

  deleteImage(docRelationName, index: number) {
    // this.user[docRelationName].url = '';
    // this.user[docRelationName].id = '';
    this.request[docRelationName].reset();
    // vaghti reset mikardam baz moshkel dasht vase hamin barabr kahli gharar dadam
    this.request[docRelationName]['url'] = '';
    delete this.progressbar[index];
  }

  openImage(Url) {
    console.log('url is ', Url);
    const album = {
      src: Url,
      caption: 'نسخه',
      thumb: Url,
    };
    this._lightbox.open([album]);
  }

  uniSelected(uni) {
    for (let key in uni.units) {
      let unit = this.units.$toArray.filter(units => {
        if (uni.units[key].id === units.id) {
          return units;
        }
      });
      this.unitsArray.push(Object.assign({}, unit));
    }

    // uni.units.$toArray.forEach(unit => {
    //   this.units.$toArray.filter(units => {
    //     return unit.id === units.id;
    //   });
    // });
  }
}
