import {Component, Input, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {AuthService} from '../service/auth.service';
import {RewardByUserModel} from '../models/reward-by-user.model';
import {DataResult, GroupDescriptor, process} from '@progress/kendo-data-query';

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

  @Input() selectedBrokerId = '';
  public gridData: RewardByUserModel[] = [] ;
  public loading = false;

  public groups: GroupDescriptor[] = [{ field: 'Description' }, { field: 'Item' } ];
  public gridView: DataResult;

  constructor(private http: HttpClient, private auth: AuthService ) { }

  ngOnInit(): void {
    this.loading = true;
    this.loadBrokerReward();
  }

  private loadBrokerReward(): void {
    this.gridData = [];

    // avoid loading everything when used with admin user
    if ( this.auth.loggedIn.role === 'admin' && this.selectedBrokerId === '' ) {
      this.loading = false;
      return ;
    }

    // load a single user
    this.http.get<RewardByUserModel[]>(this.auth.getUrl('user-reward/' + this.selectedBrokerId )).subscribe(
      rsp => {
        rsp.forEach(v => {
          this.gridData.push(new RewardByUserModel(v));
        });
        this.loadRewards();
        this.loading = false;
      }
    );
  }

  public groupChange(groups: GroupDescriptor[]): void {
    this.groups = groups;
    this.loadRewards();
  }

  private loadRewards(): void {
    this.loading = true;
    this.gridView = process(this.gridData, { group: this.groups });
    this.loading = false;
  }

  public ShowBroker(id: string): void {
    if (id === 'some-broker-that-not-exist' ) {
      this.gridView.data = [];
      this.gridView.total = 0;
      return;
    }

    this.loading = true;
    this.selectedBrokerId = id;
    this.loadBrokerReward();
  }
}
