import {Component, ViewChild} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {NgForm} from "@angular/forms";
import {WarService} from "../../services/war-service/war.service";
import {War} from "../../models/model-interfaces";


@Component({
  selector: 'war-submit',
  templateUrl: './war-submit.component.html',
  styleUrls: ['./war-submit.component.css']
})
export class WarSubmitComponent {

  war: War = {date: new Date().toISOString().slice(0, 10), players: []};

  fileList: FileList;

  showImageError = false;

  showErrorLabel = false;

  loading = false;

  error;

  @ViewChild(NgForm) form: NgForm;

  constructor(private route: ActivatedRoute,
              private router: Router,
              private warService: WarService) {
  }

  fileChange(event) {
    if (!event.target.files[0].name.endsWith('.rpt')
      && !event.target.files[0].name.endsWith('.log')
      && !event.target.files[0].name.endsWith('.txt')) {
      this.showImageError = true;
      this.fileList = undefined;
    } else {
      this.showImageError = false;
      this.fileList = event.target.files;
    }
  }

  saveWar() {
    let file: File;
    console.log(this.war.date)
    if (this.fileList) {
      file = this.fileList[0];
      this.loading = true;

      this.warService.submitWar(this.war, file)
        .subscribe(war => {
            this.router.navigate([war._id], {relativeTo: this.route});
          },
          error => {
            this.error = error._body.error.message;
            this.showErrorLabel = true;
            this.loading = false;
          });
    } else {
      return window.alert(`Logfile ist ein Pflichtfeld`);
    }
  }

  cancel() {
    this.router.navigate(['..'], {relativeTo: this.route});
    return false;
  }

}