import { Component, OnInit, HostListener } from '@angular/core';
import { TrainingRoom } from 'src/app/models/training-room.model';
import { SubscriptionSelection } from 'src/app/models/subscription-selection.model';
import { SelectionModel } from '@angular/cdk/collections';
import { SubscriptionService } from 'src/app/services/subscription.service';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { UtilsService } from 'src/app/services/utils.service';

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

  //detail
  room:TrainingRoom;
  isMobile:boolean;

  //paginator
  length:number = 0;

  //data
  subscription_selection:SubscriptionSelection;
  training_rooms:TrainingRoom[];

  //table
  master_checkbox:boolean = false;
  selection:SelectionModel<TrainingRoom> = new SelectionModel(true);

  //filtering and sorting
  params:any;

  constructor(private subscriptionService:SubscriptionService,
              private api:HitAWodService,
              private utilsService:UtilsService) { }

  ngOnInit(): void {
    this.isMobile = window.matchMedia("(max-width: 992px)").matches;
    this.subscriptionService.currentSubscription.subscribe(
      data => {
        if(data.level==="Box") {
          this.subscription_selection = data;
          this.initData();
        }
        else {
          this.utilsService.showMessage("warning", "Seleccione un box", "Necesita seleccionar un box para poder editar sus salas de entrenamiento.");
        }
      }
    );
  }

  @HostListener('window:resize', ['$event'])
  onResize(e) {
    this.isMobile = e.target.innerWidth < 992;
  }

  pageChange(num:number) {
    this.selection.clear();
    this.params.page_number = num;
    this.fetchRooms();
  }

  setMasterToggleValue() {
    if(this.selection.selected.length === this.params.page_size) {
      this.master_checkbox = true;
    }
    else this.master_checkbox = false;
  }

  masterToggle(val:boolean) {
    this.master_checkbox = val;
    if(this.master_checkbox) {
      //els hem de seleccionar tots
      this.training_rooms.forEach(r => {
        if(!this.selection.isSelected(r)) this.selection.select(r);
      });
    }
    else {
      //els hem de deseleccionar tots
      this.selection.clear();
    }
  }

  setSort(col:string) {
    this.selection.clear();
    this.params.page_number = 0;
    if(col === this.params.sort_col) {
      //estem ordenant per la mateixa, vol dir que vol canviar la direccio nomes
      if(this.params.sort_dir === "desc") this.params.sort_dir = "asc";
      else if(this.params.sort_dir === "asc") {
        this.params.sort_col = "id";
        this.params.sort_dir = "desc";
      }
    }
    else {
      //vol dir que estem ordenant per una col nova
      this.params.sort_dir = "desc";
      this.params.sort_col = col;
    }

    this.fetchRooms();
  }

  deleteSelected(index:number = 0) {
    if(index==0 && !confirm("¿Estás seguro que quieres eliminar estas salas de entrenamiento?")) return;

    if(index < this.selection.selected.length) {
      //eliminem
      this.api.deleteTrainingRoom(this.selection.selected[index].id.toString()).subscribe(
        data => {
          this.deleteSelected(index+1);
        }
      );
    }
    else {
      this.selection.clear();
      this.fetchRooms();
    }
  }

  createNew() {
    this.room = new TrainingRoom();
  }

  saveRoom() {
    if(this.room.id) {
      this.api.putTrainingRoom(this.room).subscribe(
        data => {
          this.room = null;
          this.fetchRooms();
        }
      );
    }
    else {
      if(!this.room.box_id) {
        this.room.box_id = this.subscription_selection.box.id;
      }
  
      this.api.postTrainingRoom(this.room).subscribe(
        data => {
          this.room = null;
          this.fetchRooms();
        }
      );
    }
  }

  private initData() {
    this.params = {
      sort_col: 'id',
      sort_dir: 'desc',
      page_size: 10,
      page_number: 0,
    };
    this.fetchRooms();
  }

  private fetchRooms() {
    this.api.getBoxTrainingRooms(this.subscription_selection.box.id.toString(), this.params).subscribe(
      data => {
        this.length = data.total;
        this.training_rooms = data.data;
      }
    );
  }

}
