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

import { FundService } from '../../../services/fund.service';

import { FundRecordData } from '../../../structures/fund-record-data';

import { EditFundTransactionDialogComponent } from '../../../instructor/components/edit-fund-transaction-dialog/edit-fund-transaction-dialog.component';

import { emptyFundRecordFactory } from '../../../empty-objects/empty-fund-record';

import * as Globals from '../../../globals';
import { count } from 'rxjs/operators';

@Component({
  selector: 'app-instructor-fund-detail',
  templateUrl: './instructor-fund-detail.component.html',
  styleUrls: ['./instructor-fund-detail.component.scss']
})
export class InstructorFundDetailComponent implements OnInit {

  @Input() fund: FundRecordData[] = [];
  @Input() instructorId: number = 0;

  actualFundSum : number = 0;

  showTable: boolean = false;

  fundSavingStatus: number = Globals.savingStatus.none;

  constructor(public dialog: MatDialog, private fundService: FundService) {

    this.fundService.saveStatusReset();
    this.fundService.fundRecordSaveStatus$.subscribe( val => this.fundSavingStatus = val );
  }

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

  ngOnChanges() {
    this.countSum();
  } 

  countSum() {
    this.actualFundSum = 0;
    this.fund?.forEach(fundRecord => { this.actualFundSum += fundRecord.amount; });
  }
 
  openEditTransactionDialog(id: number = 0, positive: boolean = true): void {
    var transaction = emptyFundRecordFactory();
    transaction.personId = this.instructorId;

    const dialogRef = this.dialog.open(EditFundTransactionDialogComponent, {
      data: { transaction: transaction }
    });

    dialogRef.afterClosed().subscribe(savedTransaction => {
      if(savedTransaction != undefined) {
        this.fundService.saveFund(savedTransaction);
      }
    });
  }
}
