import {Component, OnInit} from '@angular/core';
import {Event, EventService, RegisterEventRequest} from "../../services/event.service";
import {ActivatedRoute} from "@angular/router";
import {NavigationService} from "../../services/navigation.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ToastrService} from "ngx-toastr";
import {RegistrationErrors, TimeTableFilter} from "../../app.types";
import {Select} from "@ngxs/store";
import {AppState} from "../../state/app.state";
import {Observable} from "rxjs";
import {first} from "rxjs/operators";

@Component({
  selector: 'app-event-details',
  templateUrl: './event-details.component.html',
  styleUrls: ['./event-details.component.scss']
})
export class EventDetailsComponent implements OnInit {

  @Select(AppState.getFilterTimeTable) timeTableFilter: Observable<TimeTableFilter>;

  event: Event;

  eventForm: FormGroup;
  formControls: any;

  constructor(
    private fb: FormBuilder,
    private eventService: EventService,
    private route: ActivatedRoute,
    private navigationService: NavigationService,
    private toastr: ToastrService
  ) {
    this.formControls = {
      idEvent: ["", [Validators.required]],
    }
    this.eventForm = this.fb.group(this.formControls);

  }

  ngOnInit() {
    let idEvent = +this.route.snapshot.paramMap.get('idEvent');
    this.eventService.findEvent(idEvent).subscribe(
      event => {
        this.event = event;
        this.eventForm.patchValue({"idEvent": this.event.id})
      }
    );
  }

  mayRegister(event: Event) {
    return event.hasFreeSeats && !event.deleted_at && event.registrations.length == 0;
  }

  mayCancel(event: Event) {
    return event.registrations.length > 0;
  }

  goBack() {
    this.timeTableFilter.pipe(first()).subscribe(
      value => {
        this.navigationService.navigateToHome(value.idTrainer,value.idEventType);
      }
    )
  }

  register(event: Event) {

    let request: RegisterEventRequest = {
      idEvent: this.eventForm.value.idEvent,
      equipment: []
    };

    this.eventService.register(request)
      .subscribe(
        value => {
          this.toastr.success('Sikeres Foglalás', 'Foglalás');

          this.goBack();
        },
        error => {
          let status = error.status;
          let code = error?.error?.code;
          let message = "Hiba történt";
          if (status == 400) {
            switch (code) {
              case RegistrationErrors.ALREADY_REGISTERED:
                message = "Már regisztárlt  erre az edzésre!";
                break;
              case RegistrationErrors.MAX_SEAT_COUNT_EXCEEDED:
                message = "Már nem áll rendelkezésre több foglalható alkalom a bérletén!"
                break;
              case RegistrationErrors.TICKET_INSUFFICIENT:
              case RegistrationErrors.TICKET_NOT_FOUND:
                message = "Nem rendelkezik megfelelő bérlettel!"
                break;
              case RegistrationErrors.NO_FREE_SEATS:
                message = "Nincs több szabad hely!"
                break;
              case RegistrationErrors.EVENT_START_DATE_IN_PAST:
                message = "Nem lehet regisztrálni! Az esemény már elkezdődött!"
                break;
            }
          }

          this.toastr.error(message, "Foglalás")
        },
      );
  }

  cancel(event: Event) {
    this.eventService.cancelRegistration(event.registrations[0].id)
      .subscribe(
        () => {
          this.toastr.success("Sikeres lemondás", "Lemondás")
         this.goBack();
        },
        (error) => {
          let status = error.status;
          let code = error?.error?.code;
          let message = "Hiba történt";
          if (status == 400) {
            switch (code) {
              case RegistrationErrors.CANCEL_TIME_LIMIT_REACHED:
                message = "Már nem lehet lemondani a regisztrációt!";
                break;
            }
          }
          this.toastr.error(message, "Lemondás")
        });
  }

}

