import { Component, OnInit, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';

import { VoucherService } from './../../../services/voucher.service';
import { QuotaService } from './../../../services/quota.service';

@Component({
  selector: 'app-account-voucher',
  templateUrl: './voucher.component.html',
  styleUrls: ['./voucher.component.scss']
})
export class VoucherComponent implements OnInit {

  public hasRegistration: boolean = false;
  model: any = {};
  vouchers = [];
  voucherSource = new MatTableDataSource<any>();
  voucherColumns = ['type', 'code'];

  constructor(private voucherService: VoucherService, private quotaService: QuotaService, public dialog: MatDialog) { }

  ngOnInit(): void {
    this.voucherSource.data = this.vouchers;
    this.quotaService.quotas().subscribe((data: any) => {
      this.hasRegistration = data && data.some(function (quota) {
        return quota.name == "registration_vouchers" && quota.value > 0;
      })
    })
  }

  registration() {
    this.voucherService.registration().toPromise().then(data => {
      this.model.type = "registration";
      this.model.code = data;
      this.vouchers.push(this.model);
      this.voucherSource.data = this.vouchers;
      const dialogRef = this.dialog.open(VoucherDialog, {
        closeOnNavigation: false,
        disableClose: true,
        data: this.model
      });
    }, error => {

    })
  }

  addon() {
    this.voucherService.addon().subscribe((data: any) => {
      this.model.type = "add-on";
      this.model.code = data;
      this.vouchers.push(this.model);
      this.voucherSource.data = this.vouchers;
      const dialogRef = this.dialog.open(VoucherDialog, {
        closeOnNavigation: false,
        disableClose: true,
        data: this.model
      });
    }, error => {
    })
  }

}


@Component({
  selector: 'app-voucher-dialog',
  templateUrl: 'voucher.dialog.html',
  styleUrls: ['./voucher.dialog.scss']
})
export class VoucherDialog {

  constructor(public dialogRef: MatDialogRef<VoucherDialog>,
    @Inject(MAT_DIALOG_DATA) public data: any) { }

  onOkClick(): void {
    this.dialogRef.close();
  }

}