import { Component, OnInit, AfterViewInit } from '@angular/core';
import { UtilsService } from 'src/app/services/utils.service';
import { Observable } from 'rxjs';
import { AuthenticationService } from 'src/app/services/authentication.service';
import { Router, ActivatedRoute } from '@angular/router';
import { UserService } from 'src/app/services/user.service';
import { SubscriptionSelection } from '../../models/subscription-selection.model';
import { SubscriptionService } from 'src/app/services/subscription.service';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { UserSubscription } from 'src/app/models/user-subscription.model';


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

  menuActive:boolean = false;
  dropdownsActive:boolean = false;
  loading_active:Observable<boolean>;
  active_subscription_option:SubscriptionSelection;
  subscriptions_options:SubscriptionSelection[] = [];
  showContactoPopUp:boolean = false;

  constructor(private utils:UtilsService,
              private auth:AuthenticationService,
              private router:Router,
              public userService:UserService,
              public subscriptionService:SubscriptionService,
              private api:HitAWodService,
              private activatedRoute:ActivatedRoute) { }

  ngOnInit(): void {
    if(this.activatedRoute.snapshot.queryParamMap.get("start")) this.router.navigate([], { queryParams: {"start":null}, queryParamsHandling: "merge" }); //eliminem start

    this.loading_active = this.utils.getLoadingAsObservable();
    this.auth.authStatus.subscribe(
      loggedIn => {
        if(!loggedIn) {
          this.actionAfterLogout();
        }
      }
    );
  }
    
  ngAfterViewInit() {
    this.initSubscriptionsOptions();
  }

  closeMenu() {

  }

  logout() {
    this.auth.logout();
    this.subscriptionService.removeSubscription();
    this.actionAfterLogout();
  }

  setSubscriptionOption(val:SubscriptionSelection) {
    this.active_subscription_option = val;
    this.subscriptionService.setSubscription(this.active_subscription_option)
  }

  private initSubscriptionsOptions() {
    this.subscriptions_options = [];
    this.userService.currentUser.subscribe(
      user => {
        if(user) this.subscriptionService.updateSubscriptions(user.subscriptions_selections);
      }
    );
    this.subscriptionService.subscriptionsList.subscribe(
      data => {
        this.subscriptions_options = data;
      }
    );
    this.subscriptionService.currentSubscription.subscribe(
      data => {
        this.active_subscription_option = data;
      }
    );
  }

  private actionAfterLogout() {
    this.router.navigate(["/auth", "login"]);
  }

  public openContacto() { this.showContactoPopUp = true; }

}
