import { Injectable } from '@angular/core';
import { SubscriptionSelection } from '../models/subscription-selection.model';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
import { Observable } from 'rxjs';
import { UtilsService } from './utils.service';
import { UserSubscription } from '../models/user-subscription.model';
import { HitAWodService } from './hit-a-wod.service';
import { UserService } from './user.service';
import { AuthenticationService } from './authentication.service';
import { ActivatedRoute } from '@angular/router';
import { TokenService } from './token.service';

@Injectable({
  providedIn: 'root'
})
export class SubscriptionService {

  private local_storage_key = "hit-a-wod-active-subscription";

  private subscriptionsSubject:BehaviorSubject<SubscriptionSelection[]> = new BehaviorSubject(null);
  public subscriptionsList:Observable<SubscriptionSelection[]> = this.subscriptionsSubject.asObservable();

  //suscripcio seleccionada
  private subscriptionSubject:BehaviorSubject<SubscriptionSelection> = new BehaviorSubject(null);
  public currentSubscription:Observable<SubscriptionSelection> = this.subscriptionSubject.asObservable();

  constructor(private utilsService:UtilsService,
              private api:HitAWodService,
              private userService:UserService,
              private auth:AuthenticationService,
              private activatedRoute:ActivatedRoute,
              private tokenService:TokenService) {
    //load local storage subscription if exists
    let s:string;
    if((s = localStorage.getItem(this.local_storage_key))!=null){
      this.setSubscription(JSON.parse(s));
    }
  }

  public get currentSubscriptionValue():SubscriptionSelection {
    return this.subscriptionSubject.value;
  }

  public setSubscription(s:SubscriptionSelection) {
    if(s!=null && s!=undefined) {
      if(JSON.stringify(this.currentSubscriptionValue) !== JSON.stringify(s)) {
        this.saveSubscriptionToLocaleStorage(s);
        this.subscriptionSubject.next(s);
        if(s.company.active_plan == null) {
          this.utilsService.showMessage("warning", "Suscripción no activa", "Tu empresa no tiene una suscripción activa a Hit a Wod. Para que funcione correctamente, renuévala.");
        }
      }
      
    }
  }

  public removeSubscription() {
    localStorage.removeItem(this.local_storage_key);
    this.subscriptionSubject.next(null);
    this.subscriptionsSubject.next(null);
  }

  public isset():boolean {
    return this.subscriptionSubject.value != null;
  }

  public updateSubscriptions(uss:SubscriptionSelection[]) {
    uss.forEach(s => {
      if(this.auth.isRoleOk(s.role.slug)) { //Mirem que sigui coach, box o company admin          
        if(JSON.stringify(s) === JSON.stringify(this.currentSubscriptionValue)) this.setSubscription(s);
      }
      else {
        //error
        console.error("Role is not valid: ", s.role.slug);
      }
    });
    
    if(this.currentSubscriptionValue == null && uss.length > 0) 
      this.setSubscription(uss[0]);

    this.subscriptionsSubject.next(uss);
  }

  private saveSubscriptionToLocaleStorage(s:SubscriptionSelection) {
    localStorage.setItem(this.local_storage_key, JSON.stringify(s));
  }

}
