update-horse.component.ts 3.59 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params} from '@angular/router';
import { Horse } from '../../dto/horse';
import { HorseService } from '../../service/horse.service';

@Component({
  selector: 'app-update-horse',
  templateUrl: './update-horse.component.html',
  styleUrls: ['./update-horse.component.scss']
})
export class UpdateHorseComponent implements OnInit {
  error = false;
  success: string;
  errorMessage = '';
  horse: Horse = new Horse(null, null, null, null, null, null, null, null);
  imageToUpload: File = null;

  constructor(private horseService: HorseService, private route: ActivatedRoute) { }

  ngOnInit(): void {
    // Extract id from url
    const horseId: string = this.route.snapshot.paramMap.get('id');

    // Get current value of the horse and save it
    this.horseService.getHorseById(parseInt(horseId, 10)).subscribe(
      (horse: Horse) => {
        this.horse = horse;
      },
      error => {
        this.defaultServiceErrorHandling(error);
      }
    );
  }

  /**
   * Will be called on a click on the success alert close button
   */
  public vanishAlert() {
    this.success = null;
  }

  /**
   * Will be called on a click on the error alert close button
   */
  public vanishError() {
    this.errorMessage = null;
  }

  /**
   * Handles the input on the image input.
   * Inspired from:
   * https://stackoverflow.com/questions/47936183/angular-file-upload
   * @param files
   */
  public handleImageInput(files: FileList) {
    var imageFile: File = files.item(0);

    // Generate a random bytes name to avoid conflicts
    var fileExt: string = imageFile.name.split('.').pop();
    var newFileName: string = this.generateHex(20) + '.' + fileExt;
    this.horse.imagePath = newFileName;

    // Upload the file
    this.uploadFile(imageFile, newFileName)
  }

  /**
   * Updates a horse and loads it
   * @param horse
   */
  public updateHorse() {
    console.log("PUT horse to API")
    console.log(this.horse);
    // TODO: Make it possible for the horse to be added with an owner
    this.horseService.updateHorse(this.horse).subscribe(
      (result: Horse) => {
        this.success = result.name;
      },
      error => {
        this.defaultServiceErrorHandling(error);
      }
    );
  }

  /**
   * Uploads the file to the backend with the specified file name
   * @param file
   * @param newFileName
   */
  private uploadFile(file: File, newFileName: string){
    this.horseService.postFile(file, newFileName).subscribe(
      () => {
        console.log("Image successfully uploaded");
      }, error => {
        this.defaultServiceErrorHandling(error)
      });
  }

  /**
   * Generates a random hex with the specified length
   * Inspired from:
   * https://stackoverflow.com/a/27747377
   * @param len
   */
  private generateHex(len: number): string {
    var arr = new Uint8Array((len) / 2)
    window.crypto.getRandomValues(arr)
    return Array.from(arr, this.dec2hex).join('')
  }

  /**
   * Converts a decimal to its hex value
   * @param dec
   */
  private dec2hex(dec: number): string {
    return ('0' + dec.toString(16)).substr(-2)
  }

  private defaultServiceErrorHandling(error: any) {
    console.log(error);
    this.error = true;
    if (error.status === 0) {
      // If status is 0, the backend is probably down
      this.errorMessage = 'The backend seems not to be reachable';
    } else if (error.error.message === 'No message available') {
      // If no detailed error message is provided, fall back to the simple error name
      this.errorMessage = error.error.error;
    } else {
      this.errorMessage = error.error.message;
    }
  }
}