import { Component, OnInit } from '@angular/core';
import { Pricing } from 'src/app/models/pricing.model';
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 { UtilsService } from 'src/app/services/utils.service';
import { UserSubscription } from 'src/app/models/user-subscription.model';
import { Observable } from 'rxjs';
import { SelectionModel } from '@angular/cdk/collections';
import { Router } from '@angular/router';
import { User } from 'src/app/models/user.model';

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

  //paginator
  length:number = 0;
  pageSize:number = 10;
  page:number = 0;

  //filtering
  search_text:string;
  subscription_status_filter:number = 1;
  pricing_id_filter:number = -1;
  role_filter:number = 1;

  //data
  subscription_selection:SubscriptionSelection;
  pricings:Pricing[];
  user_subscriptions:UserSubscription[];

  //layout flags
  active_primary:boolean = true;
  inactive_secondary:boolean = true;
  active_secondary:boolean = true;
  active_new_user:boolean = false;
  active_new_subscription:boolean = false;

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

  //filtering and sorting
  params = {
    sort_col: 'id',
    sort_dir: 'desc',
    subscription_status: this.subscription_status_filter,
    pricing_id: this.pricing_id_filter,
    role_group: this.role_filter,
    user_name_like: this.search_text
  };

  //create user and subscription
  user_created:User;

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

  ngOnInit(): void {
    this.subscriptionService.currentSubscription.subscribe(sub => {
      this.subscription_selection = sub;
      this.initData();
    });
  }

  pageChange(num:number) {
    this.page = num;
    this.fetchUserSubscriptions();
  }

  setMasterToggleValue() {
    if(this.selection.selected.length === this.pageSize) {
      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.user_subscriptions.forEach(s => {
        if(!this.selection.isSelected(s)) this.selection.select(s);
      });
    }
    else {
      //els hem de deseleccionar tots
      this.selection.clear();
    }
  }

  setSort(col:string) {
    this.page = 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.fetchUserSubscriptions();
  }

  setStatusFilter(val:number) {
    this.subscription_status_filter = val;
    this.params.subscription_status = val;
    this.page = 0;
    this.fetchUserSubscriptions();
  }

  setPricingFilter(val:number) {
    this.pricing_id_filter = val;
    this.params.pricing_id = val;
    this.page = 0;
    this.fetchUserSubscriptions();
  }

  setRoleFilter(val:number) {
    this.role_filter = val;
    this.params.role_group = val;
    this.page = 0;
    this.fetchUserSubscriptions();
  }

  searchByUserName(val:string) {
    this.search_text = val;
    if(val && val.length > 3) {
      this.params.user_name_like = val;
      this.page = 0;
      this.fetchUserSubscriptions();
    }
    else if(this.params.user_name_like != null) {
      this.params.user_name_like = null;
      this.page = 0;
      this.fetchUserSubscriptions();
    }
  }

  newSubscriptionEvent(us:UserSubscription) {
    this.active_new_subscription = false;
    if(us!=null) {
      this.router.navigate(["/admin", "subscriptions", us.id]);
    }
  }

  createdUserEvent(user:User) {
    this.active_new_user = false;
    if(user!=null) {
      this.user_created = user;
      this.active_new_subscription = true;
    }
  }

  private initData() {
    this.fetchPricings();
    this.fetchUserSubscriptions();
  }

  private fetchPricings() {
    if(this.subscription_selection.level==="Company") {
      this.api.companyPricings(this.subscription_selection.company.id).subscribe(
        data => {
          this.pricings = data.data;
        }
      );
    }
    else if(this.subscription_selection.level==="Box") {
      this.api.getBoxPricings(this.subscription_selection.box.id.toString()).subscribe(
        data => {
          this.pricings = data.data;
        }
      );
    }
    else this.utilsService.showMessage("error", "Error en la suscripción seleccionada", "El tipo de suscripción no ha sido identificado. Contacte con soporte.");
  }

  private fetchUserSubscriptions() {
    if(this.subscription_selection.level === "Company") {
      this.api.getCompanyUserSubscriptions(this.subscription_selection.company.id.toString(), this.pageSize, this.page, this.params).subscribe(
        data => {
          this.user_subscriptions = data.data;
          this.length = data.total;
        }
      );
    }
    else if(this.subscription_selection.level === "Box") {
      this.api.getBoxUserSubscriptions(this.subscription_selection.box.id.toString(), this.pageSize, this.page, this.params).subscribe(
        data => {
          this.length = data.total;
          this.user_subscriptions = data.data;
        }
      );
    }
    else this.utilsService.showMessage("error", "Error en la suscripción seleccionada", "El tipo de suscripción no ha sido identificado. Contacte con soporte.");
  }

}
