import { Component, Inject, OnInit } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { NotificationService } from '@shared/ui-api/notification.service';
import { catchError } from 'rxjs/operators';
import { EMPTY } from 'rxjs';
import { IPricingPlanModel } from '@fleio-api/openstack/model/pricing-plan.model';
import { IServiceModel } from '@fleio-api/billing/model/service.model';
import { PricingPlansApiService } from '@fleio-api/openstack/pricing-plan/pricing-plans-api.service';
import { ServicesApiService } from '@fleio-api/billing/services/service-api.service';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';


@Component({
  selector: 'app-change-pricing-plan-dialog',
  templateUrl: './change-pricing-plan-dialog.component.html',
  styleUrls: ['./change-pricing-plan-dialog.component.scss']
})
export class ChangePricingPlanDialogComponent implements IBaseDialog, OnInit {
  changePlanFrom = this.formBuilder.group({
    selectedPlan: [null, Validators.required]
  });
  dialogTitle = $localize`Change service pricing plan`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Change plan`,
      primary: true,
      callback: () => this.changePlan(),
    }),
  ];
  dialogForm = this.changePlanFrom;

  selectedPlan = this.changePlanFrom.controls.selectedPlan;
  currentPlan: IPricingPlanModel;
  availablePlans: Array<IPricingPlanModel>;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<ChangePricingPlanDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      client: IClientModel;
      service: IServiceModel;
      availablePlans: Array<IPricingPlanModel>;
    },
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
    private pricingPlansApi: PricingPlansApiService,
    private servicesApi: ServicesApiService,
    private clientsApiService: ClientsApiService,
  ) {
  }

  ngOnInit() {
    if (this.data && this.data.service) {
      this.currentPlan = this.data.service.pricing_plan;
    }
    if (this.data && !this.data.availablePlans) {
      this.loading = true;
      this.pricingPlansApi.list().subscribe(availablePlans => {
        this.availablePlans = availablePlans.objects.filter(plan => plan.name !== this.currentPlan.name);
        this.loading = false;
      });
    } else {
      this.availablePlans = this.data.availablePlans.filter(plan => plan.name !== this.currentPlan.name);
    }
  }

  hasOnlySelectedPlan() {
    if (this.availablePlans && this.availablePlans.length === 1 && this.currentPlan) {
      if (this.availablePlans[0].id === this.currentPlan.id) {
        return true;
      }
    }
    return false;
  }

  changePlan() {
    this.loading = true;
    this.servicesApi.updateBillingPlan(this.data.service.id, this.selectedPlan.value).pipe(
      catchError(() => {
        this.notificationService.showMessage($localize`Failed to change pricing plan`);
        return EMPTY;
      }),
    ).subscribe(() => {
      this.dialogRef.close(true);
    }).add(() => {
      this.loading = false;
    });
  }
}
