import {Component, Inject} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Dialog} from '../../../../classes/base_components/dialog/dialog';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import {setErrors} from '../../../../classes/utils';
import {RequestsService, Requests} from '../../../../classes/resorcess/requests.service';
import {Lightbox} from 'ngx-lightbox';
import {HttpClient, HttpEventType} from '@angular/common/http';
import {environment} from '../../../../../environments/environment';
import {Base} from 'ngx-jsonapi/services/base';
import {Type, TypesService} from '../../../../classes/resorcess/types.service';

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


export class EditRequestsComponent {
  formatFilter  = '.jpg, .png, .jpeg|image/*';
  public loading = false;
  nameCtrl = new FormControl();
  statusCtrl = 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();
  form: FormGroup;
  request: Requests;
  progressbar = [0, 0];
  selectedFile: File = null;
  types;


  constructor(private fb: FormBuilder,
              public requestService: RequestsService,
              protected  dialog: Dialog,
              public  dialogRef: MatDialogRef<EditRequestsComponent>,
              @Inject(MAT_DIALOG_DATA)  data,
              private _lightbox: Lightbox,
              private http: HttpClient,
  ) {
    this.request = data;
    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,
    });
    const  basics = JSON.parse(localStorage.getItem('basics'));
    this.types = Base.newCollection<Type>();
    (new TypesService()).convert(JSON.parse(basics['types']), this.types);
  }

  onSubmit() {
    this.loading = true;
    if (!this.form.valid) {
      this.loading = false;
      return;
    }
    this.request.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);
  }
  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]);
  }
}
