import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { ServicesApiService } from '@fleio-api/billing/services/service-api.service';
import { IServiceModel } from '@fleio-api/billing/model/service.model';
import { ConfigService } from '@shared/config/config.service';
import { LineColorPipe } from '@shared/ui/objects-view/status-line/line-color.pipe';
import { IObjectStatus, StatusType, StatusValue } from '@objects-view/interfaces/object-status';
import { LineDirection } from '@shared/ui/objects-view/status-line/status-line.component';
import { LineType } from '@shared/ui/objects-view/status-line/status-line.component';

@Component({
  selector: 'app-client-details-services',
  templateUrl: './client-details-services.component.html',
  styleUrls: ['./client-details-services.component.scss']
})
export class ClientDetailsServicesComponent extends DetailsComponentBase<IClientModel> implements OnInit {
  displayedColumns: string[] = ['display_name', 'cycle', 'activated', 'paid_until', 'status'];
  services: IServiceModel[];

  private lineColorPipe: LineColorPipe;
  protected readonly LineType = LineType;
  protected readonly LineDirection = LineDirection;

  constructor(
    private servicesApiService: ServicesApiService,
    public config: ConfigService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
    this.lineColorPipe = new LineColorPipe();
  }

  ngOnInit() {
    super.ngOnInit();
  }

  getServiceStatus(service: IServiceModel): IObjectStatus {
    switch (service.status) {
      case 'active':
        return {type: StatusType.Defined, value: StatusValue.Active};
      case 'pending':
        return {type: StatusType.Defined, value: StatusValue.Pending};
      case 'suspended':
        return {type: StatusType.Defined, value: StatusValue.Suspended};
      case 'terminated':
        return {type: StatusType.Defined, value: StatusValue.Terminated};
      case 'canceled':
        return {type: StatusType.Defined, value: StatusValue.Canceled};
      case 'deleting':
        return {type: StatusType.Changing, value: StatusValue.Deleted};
      default:
        return {type: StatusType.None, value: StatusValue.None};
    }
  }

  protected refreshData() {
    this.servicesApiService.list({
      client: this.object.id,
      page_size: 50,
    }).subscribe(servicesResp => {
      this.services = servicesResp.objects;
      for (const service of this.services) {
        let serviceStatus = this.getServiceStatus(service);
        (service as any).appLineColor = this.lineColorPipe.transform(serviceStatus.value);
        (service as any).appLineType = serviceStatus.type === StatusType.Changing ? LineType.Progress : LineType.Solid;
      }
    });
  }

}
