import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { User } from 'src/app/models/user.model';
import { Pricing } from 'src/app/models/pricing.model';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { UserSubscription } from 'src/app/models/user-subscription.model';
import { SubscriptionSelection } from 'src/app/models/subscription-selection.model';
import { Role } from 'src/app/models/role.model';
import { Discount } from 'src/app/models/discount.model';

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

  //inputs and outputs
  @Input() pricings:Pricing[];
  @Input() box_id:number;
  @Input() user_default:User;
  @Input() company_id:number;
  @Output() close:EventEmitter<UserSubscription> = new EventEmitter();
  
  //atributs
  user_id:number;
  filtered_users:User[];
  pricing_id:number;
  roles:Role[];
  role_id:number;
  matricula_amount:number;
  discount_id:number;
  discounts:Discount[];
  accept:Boolean = false;

  constructor(private api:HitAWodService) { }

  ngOnInit(): void {
    this.fetchRoles();
    this.fetchDiscounts();
    this.pricing_id = this.pricings[0].id;

    //inicialitzem usuari creat per parametre per defecte
    if(this.user_default != null) {
      this.filtered_users = [ this.user_default ];
      this.user_id = this.user_default.id;
    }
  }

  searchUsers(val:string) {
    this.api.getUsers({name: val, surnames: val, email: val}).subscribe(
      data => {
        this.filtered_users = data.data;
      }
    );
  }

  createSubscription() {
    this.api.generateUserSubscription({ 
      box_id: this.box_id,
      pricing_id: this.pricing_id,
      role_id: this.role_id,
      user_id: this.user_id,
      renew: 0,
      payment_type_id: 2, //cash
      matricula: this.matricula_amount,
      discount_id: this.discount_id
     }).subscribe(
      data => {
        this.close.emit(data);
      }
    );
  }

  fetchRoles() {
    this.api.getAllRoles().subscribe(
      data => {
        this.roles = data;
        this.role_id = this.roles[0].id;
      }
    );
  }

  fetchDiscounts() {
    this.api.companyDiscounts(this.company_id, true).subscribe(
      data => {
        this.discounts = data.data;
      }
    );
  }

}
