import { Component, OnInit, Input } from '@angular/core';
import { BoxOrder } from 'src/app/models/box-order.model';
import { UserSubscription } from 'src/app/models/user-subscription.model';
import { User } from 'src/app/models/user.model';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { Router } from '@angular/router';
import { UtilsService } from 'src/app/services/utils.service';
import * as moment from 'moment';

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

  @Input() subscription_id: number;
  @Input() subscription: UserSubscription;
  @Input() user: User;
  now:Date = new Date();

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

  ngOnInit(): void {
    if(this.subscription == null) {
      this.fetchSubscription();
    }
    else if(this.user == null) {
      if(this.subscription.user != null) this.user = this.subscription.user;
      else this.fetchUser();
    }
  }

  getChipStatusText() {
    let diff = moment(this.subscription.end_date).diff(this.now, 'days');
    let diff2 = moment(this.subscription.start_date).diff(this.now, 'days');
    return !this.subscription.active ?
      'No activa' :
      ((diff <= 7 && diff > 0) ?
        'Finaliza en ' + diff + ' días' :
        (diff <= 0 ?
          'En prórroga' :
          (diff2 > 0 ?
            'Empieza en ' + diff2 + ' días' :
            'Activa'
          )
        )
      )
  }

  private fetchSubscription() {
    if (this.subscription_id) {
      this.api.getUserSubscription(this.subscription_id.toString()).subscribe( s => {
        this.subscription = s;
        this.fetchUser();
      });
    }
  }

  public navigateToSubscription() {
    this.router.navigateByUrl(`admin/subscriptions/${this.subscription_id}`);
  }
  
  private fetchUser() {
    this.api.getUser(this.subscription.user_id.toString()).subscribe( u => {
      this.user = u;
    });  
  }

}
