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

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

  //detail
  new:New;
  isMobile:boolean;

  //paginator
  length:number = 0;

  //data
  subscription_selection:SubscriptionSelection;
  news:New[];
  boxes:Box[];

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

  //filtering and sorting
  search_box:string;
  level_filter:string;
  params:any;

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

  ngOnInit(): void {
    this.isMobile = window.matchMedia("(max-width: 992px)").matches;
    this.subscriptionService.currentSubscription.subscribe(
      data => {
        if(data.role.slug === "box_admin" || data.role.slug==="company_admin") {
          this.subscription_selection = data;
          this.initData();
        }
      }
    );
  }

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

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

  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.news.forEach(n => {
        if(!this.selection.isSelected(n)) this.selection.select(n);
      });
    }
    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.fetchNews();
  }

  searchByNewTitle(val:string) {
    this.search_box = val;
    this.selection.clear();
    if(val && val.length > 3) {
      this.params.title = val;
      this.params.page_number = 0;
      this.fetchNews();
    }
    else if(this.params.title != null) {
      this.params.title = null;
      this.params.page_number = 0;
      this.fetchNews();
    }
  }

  filterByLevel(val:string) {
    if(val && val!="") {
      this.level_filter = val;
      this.selection.clear();
      this.params.page_number = 0;
      if(val==="global") {
        this.params.company_id = this.subscription_selection.company.id;
        this.params.box_id = null;
        this.fetchNews();
      }
      else if(val==="box") {
        this.params.box_id = this.subscription_selection.box.id;
        this.params.company_id = null;
        this.fetchNews();
      }
    }
    else {
      this.level_filter = null;
      delete this.params.box_id;
      delete this.params.company_id;
      this.fetchNews();
    }
  }

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

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

  createNew() {
    this.new = new New();
  }

  saveNew() {
    if(this.new.id) {
      this.api.putNew(this.new).subscribe(
        data => {
          this.new = data;
          this.fetchNews();
        }
      );
    }
    else {
      if(!this.new.box_id && !this.new.company_id) {
        if(this.subscription_selection.level === "Box") this.new.box_id = this.subscription_selection.box.id;
        else this.new.company_id = this.subscription_selection.company.id;
      }
  
      this.api.postNew(this.new).subscribe(
        data => {
          this.new = data;
          this.fetchNews();
        }
      );
    }
  }

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

    if(this.subscription_selection.role.slug == "company_admin" || this.subscription_selection.role.slug == "super_admin") 
      this.fetchBoxes();
  }

  private fetchNews() {
    if(this.subscription_selection.level === "Company") {
      this.api.companyNews(this.subscription_selection.company.id, this.params).subscribe(
        data => {
          this.length = data.total;
          this.news = data.data;
        }
      );
    }
    else if(this.subscription_selection.level === "Box") {
      this.api.getBoxNews(this.subscription_selection.box.id.toString(), this.params).subscribe(
        data => {
          this.length = data.total;
          this.news = data.data;
        }
      );
    }
  }

  private fetchBoxes() {
    this.api.companyBoxes(this.subscription_selection.company.id).subscribe(
      data => {
        this.boxes = data.data;
      }
    );
  }

}
