import { Component, OnInit } from '@angular/core';
import { IServiceDynamicUsageModel } from '@fleio-api/billing/model/service-dynamic-usage.model';
import {
  ServiceDynamicUsagesApiService
} from '@fleio-api/billing/service-dynamic-usage/service-dynamic-usages-api.service';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { ConfigService } from '@shared/config/config.service';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { FormBuilder } from '@angular/forms';
import { BillingHistoryObjectList } from '@fleio-api/billing/billing-history/billing-history-api.service';

@Component({
  selector: 'app-client-details-billing',
  templateUrl: './client-details-billing.component.html',
  styleUrls: ['./client-details-billing.component.scss']
})
export class ClientDetailsBillingComponent extends DetailsComponentBase<IClientModel> implements OnInit {
  serviceDynamicUsageList: BillingHistoryObjectList<IServiceDynamicUsageModel> = null;
  incomeSDUList: IServiceDynamicUsageModel[] = null;
  dynamicUsage: IServiceDynamicUsageModel = null;
  loading = false;
  usageSelectForm = this.formBuilder.group({
    currentUsageId: [null],
  });
  currentUsageId = this.usageSelectForm.controls.currentUsageId;
  selectedUsageId;

  constructor(
    private serviceDynamicUsagesApiService: ServiceDynamicUsagesApiService,
    private formBuilder: FormBuilder,
    public config: ConfigService,
  ) {
    super();
  }

  selectFirstServiceDynamicUsage() {
    this.dynamicUsage = this.incomeSDUList[0];
    if (this.dynamicUsage) {
      this.selectedUsageId = this.dynamicUsage.id;
      this.currentUsageId.setValue(this.dynamicUsage.id);
    }
  }

  loadDynamicUsage(id: FleioId) {
    this.loading = true;
    this.serviceDynamicUsagesApiService.get(id).subscribe(history => {
      this.dynamicUsage = history;
      this.selectedUsageId = id;
    }).add(() => {
      this.loading = false;
    });
  }

  getPrev() {
    if (this.dynamicUsage.previous_history) {
      this.loadDynamicUsage(this.dynamicUsage.previous_history);
    } else {
      console.error('Get prev called for service usage with no previous history');
    }
  }

  getNext() {
    if (this.dynamicUsage.next_history) {
      this.loadDynamicUsage(this.dynamicUsage.next_history);
    } else {
      this.getCurrentUsage();
    }
  }

  getCurrentUsage() {
    if (this.currentUsageId.value) {
      // current usage value selected for a service, load it
      this.loading = true;
      this.serviceDynamicUsagesApiService.get(this.currentUsageId.value).subscribe(history => {
        this.dynamicUsage = history;
      }).add(() => {
        this.loading = false;
      });
    } else if (this.object) {
      this.loading = true;
      this.serviceDynamicUsagesApiService.getForClient(
        this.object.id,
        1
      ).subscribe({
        next: (list) => {
          this.serviceDynamicUsageList = list;
          this.incomeSDUList = [];
          for (const serviceDynamicUsage of list.objects) {
            this.incomeSDUList.push(serviceDynamicUsage);
          }
          this.selectFirstServiceDynamicUsage();
        }
      }).add(() => {
        this.loading = false;
      });
    }
  }

  protected tabActivated() {
    super.tabActivated();
    this.getCurrentUsage();
  }

  ngOnInit() {
    super.ngOnInit();
    this.currentUsageId.valueChanges.subscribe((id: FleioId) => {
      if (this.selectedUsageId !== id) {
        // user changed service selection, re-load
        this.loadDynamicUsage(id);
      }
      const service = this.serviceDynamicUsageList.available_services.find(
        availableService => availableService.related_dynamic_usage_id === id
      );
    });
  }
}
