import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AircraftService } from '../../services/aircraft.service';
import { ServiceComm } from '../../services/service-comm.service';
import { AddAction } from '../../models/add-action.enum';

@Component({
  selector: 'app-new-aircraft',
  templateUrl: './new-aircraft.component.html',
  styleUrls: ['./new-aircraft.component.css']
})
export class NewAircraftComponent implements OnInit {
  public addForm: FormGroup;
  public imageError: string;
  private selectedFile: string;

  constructor(private serviceComm: ServiceComm,
              private serviceApi: AircraftService) {
    this.addForm = new FormGroup(
      {
        aircraftName: new FormControl('', Validators.required)
      },
      { updateOn: 'blur' }
    );
  }

  ngOnInit() { }

  onSubmit(formData) {
    if (formData.invalid) {
      return;
    }

    this.serviceApi.AddAircraft(formData.aircraftName, this.selectedFile)
                   .subscribe(() => {
                    this.serviceComm.RefreshData(AddAction.Aircraft);
                   });
  }

  public onFileChanged(fileInput: any) {
    const file = fileInput.dataTransfer ? fileInput.dataTransfer.files[0] : fileInput.target.files[0];
    const allowed_types = ['image/png', 'image/jpeg'];
    const max_size = 20971520;

    if (!allowed_types.includes(file.type)) {
      this.imageError = 'Only Images are allowed ( JPG | PNG )';
    } else if (file.size > max_size) {
      this.imageError = 'Maximum size allowed is ' + max_size / 1000 + 'Mb';
    } else {
      const reader = new FileReader();
      reader.onload = this.checkAndExtractDataToBase64.bind(this);
      reader.readAsDataURL(fileInput.target.files[0]);
    }
  }

  private checkAndExtractDataToBase64(e: any) {
    const max_height = 15200;
    const max_width = 25600;

    const image = new Image();
    image.src = e.target.result;
    image.onload = (rs) => {
      const img_height = rs.currentTarget['height'];
      const img_width = rs.currentTarget['width'];

      if (img_height > max_height && img_width > max_width) {
        this.imageError =
          'Maximum dimentions allowed ' + max_height + '*' + max_width + 'px';
      } else {
        const imgBase64Path = e.target.result;
        this.selectedFile = imgBase64Path;
        this.imageError = 'OK';
      }
    };
  }
}
