import { Component, OnInit, Input, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef, HostListener } from '@angular/core';
import { CalendarEvent } from 'angular-calendar';
import { User } from 'src/app/models/user.model';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { TrainingType, TrainingWorkout } from 'src/app/models/training-workout.model';

@Component({
  selector: 'app-training-session-detail',
  templateUrl: './training-session-detail.component.html',
  styleUrls: ['./training-session-detail.component.css']
})
export class TrainingSessionDetailComponent implements OnInit, AfterViewInit {

  @ViewChild("detail") detail:ElementRef;

  @Input() ts:CalendarEvent;
  @Input() coaches:User[];
  @Input() isMobile:boolean;
  @Output() close:EventEmitter<CalendarEvent> = new EventEmitter();
  now:Date = new Date();

  athletes:User[];
  @Input() training_types:TrainingType[];
  all_workouts:TrainingWorkout[] = [];
  filtered_workouts:TrainingWorkout[] = [];

  edit:boolean = false;
  active:boolean = false;

  constructor(private api:HitAWodService) { }

  ngOnInit(): void {
    this.initWorkouts();

    if(!this.ts.meta.ts.id) this.edit = true;
    else this.fetchAthletes();
  }
  
  ngAfterViewInit() {
    this.active = true;
    const self = this;
    if(this.isMobile) {
      setTimeout(() => {
        self.detail.nativeElement.style.transform = "unset";
      }, 1500);
    }
  }

  //per quan cliquin fora del autocomplete, es plegui automaticament
  @HostListener('document:click', ['$event'])
  clickout(event) {
    if(!this.detail.nativeElement.contains(event.target)) {
      this.closeDialog();
    }
  }

  closeDialog(evt = null) {
    this.detail.nativeElement.style.transform = null;
    this.active = false;
    const self = this;
    setTimeout(() => {
      self.close.emit(evt);
    }, 800);
  }

  preventCloseDialog(event) {
    event.stopPropagation();
  }

  delete() {
    if(confirm("¿Seguro que quieres eliminar esta sesión?")) {
      this.api.deleteTrainingSession(this.ts.meta.ts.id.toString()).subscribe(
        data => {
          this.closeDialog(this.ts);
        },
        error => {
          this.closeDialog();
        }
      );
    }
  }

  save() {
    if(this.ts.meta.ts.id) {
      this.api.putTrainingSession(this.ts.meta.ts).subscribe(
        data => {
          this.edit = false;
          this.ts.meta.ts = data;
          this.closeDialog(this.ts);
        },
        error => {
  
        }
      );
    }
    else {
      this.api.postTrainingSession(this.ts.meta.ts).subscribe(
        data => {
          this.edit = false;
          this.ts.meta.ts = data;
          this.closeDialog(this.ts);
        },
        error => {
  
        }
      );
    }
  }

  setStartDatetimeLocal(evt:Date) {
    this.ts.start = evt;
    this.ts.meta.ts.date_start = evt;
  }

  setEndDatetimeLocal(evt:Date) {
    this.ts.end = evt;
    this.ts.meta.ts.date_end = evt;
  }
  
  getWorkoutNameById(id:number):string {
    let res:string = id.toString();
    if(this.all_workouts && this.all_workouts.length) {
      this.all_workouts.forEach(w => {
        if(w.id == id)
          res = w.name;
      });
    }

    return res;
  }

  filterWorkoutsByName(name:string) {
    this.api.getBoxTrainingWorkouts(this.ts.meta.ts.box_id, {name: name}).subscribe(
      data => {
        this.filtered_workouts = data.data;
      }
    );
  }

  private initWorkouts() {
    this.api.getBoxTrainingWorkouts(this.ts.meta.ts.box_id.toString()).subscribe(
      data => {
        this.all_workouts = data.data;
        this.filtered_workouts = data.data;
      }
    );
  }

  private fetchAthletes() {
    this.api.getTrainingSessionUsers(this.ts.meta.ts.id.toString()).subscribe(
      data => {
        this.athletes = data.data;
      }
    );
  }

}
