import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { SubscriptionSelection } from 'src/app/models/subscription-selection.model';
import { Plan } from 'src/app/models/plan.model';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { Subscription } from 'src/app/models/subscription.model';

@Component({
  selector: 'app-change-company-plan-dialog',
  templateUrl: './change-company-plan-dialog.component.html',
  styleUrls: ['./change-company-plan-dialog.component.css']
})
export class ChangeCompanyPlanDialogComponent implements OnInit {

  @Output() close:EventEmitter<Subscription> = new EventEmitter();

  @Input() subscriptionSelection:SubscriptionSelection;
  plans:Plan[];

  selected_plan_id:number;
  override:number = 0;

  constructor(private api:HitAWodService) { }

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

  onClose(s:Subscription = null) {
    this.close.emit(null);
  }

  change() {
    this.api.postSubscriptionSubscribe({
      company_id: this.subscriptionSelection.company.id,
      plan_id: this.selected_plan_id,
      set_date_after_current_subscription: this.override ? 0 : 1
    }).subscribe(
      data => {
        this.api.putSubscriptionPay(data.id.toString(), this.override ? true : false).subscribe(
          data => {
            this.onClose(data);
          }
        );
      }
    );
  }

  private fetchPlans() {
    this.api.getAllPlans().subscribe(
      data => {
        this.plans = data.data.filter((p:Plan) => p.id != this.subscriptionSelection.company?.active_plan.plan_id)
      }
    );
  }

}
