import { Component, OnInit, Input, Output, EventEmitter, OnChanges } from '@angular/core';
import { BoxOrder } from 'src/app/models/box-order.model';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { UserSubscription } from 'src/app/models/user-subscription.model';
import { User } from 'src/app/models/user.model';

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

  @Input() mobile:boolean = true;
  @Input() boxOrder:BoxOrder;
  @Output() close = new EventEmitter<Boolean>();

  subscription: UserSubscription;
  user: User;
  factura: boolean = false;
  invoiceHTML;

  constructor(private api: HitAWodService) { }

  ngOnInit(): void {
    this.checkSubscription();
  }

  ngOnChanges() {
    this.checkSubscription();
  }

  closeDetail() {
    this.close.emit(true);
  }

  checkSubscription() {
    let subscription_id;
    this.subscription = null;
    this.user = null;
    this.invoiceHTML = null;
    if (this.boxOrder && this.boxOrder.lines) {
      this.boxOrder.lines.forEach( l => {
        if (l.user_subscription_id) subscription_id = l.user_subscription_id;
      })

      if (subscription_id) {
        this.api.getUserSubscription(subscription_id).subscribe( s => {
          this.subscription = s;

          this.api.getUser(s.user_id.toString()).subscribe( u => {
            this.user = u;
          });
        
        });
      }
    }
  }

  verFactura() {
    this.factura = true;
    if (!this.invoiceHTML) {
      this.api.getHTMLInvoice(this.boxOrder.invoice_id.toString()).subscribe( i => {
        this.invoiceHTML = i;
      });
    }
  }

  closeFactura() {
    this.factura = false;
  }

  

}
