import { Component, OnInit, Input, ViewChild, ChangeDetectorRef, EventEmitter, Output, ViewRef } from '@angular/core';
import { RemissionProduct, RemissionService, RemissionProcess } from '@isa/remission';
import { RemissionSelectors } from 'apps/sales/src/app/core/store/selectors/remission.selectors';
import { Store } from '@ngxs/store';
import { RemissionHelperService } from '../../services/remission-helper.service';
// tslint:disable-next-line: max-line-length
import { RemissionAddProductToShippingDocumentDialogComponent } from '../remission-add-product-to-shipping-document-dialog/remission-add-product-to-shipping-document-dialog.component';

// tslint:disable-next-line: max-line-length
import { RemissionAddProductToShippingDocumentPartiallyDialogComponent } from '../remission-add-product-to-shipping-document-partially-dialog/remission-add-product-to-shipping-document-partially-dialog.component';
import { ErrorService } from 'apps/sales/src/app/core/error/component/error.service';
import { SetRemissionProcess } from 'apps/sales/src/app/core/store/actions/remission.actions';

@Component({
  selector: 'app-remission-list-card-started',
  templateUrl: './remission-list-card-started.component.html',
  styleUrls: ['./remission-list-card-started.component.scss'],
})
export class RemissionListCardStartedComponent implements OnInit {
  @Input()
  get product(): RemissionProduct {
    return this._product;
  }
  set product(value: RemissionProduct) {
    this._product = value;
    this.toolTipOpened = new Array(value.features.length).fill(false);
  }
  @Input() remissionProcess: RemissionProcess;
  @Output() updateShippingDocument = new EventEmitter<void>();

  @ViewChild('addProductDialog')
  addProductDialog: RemissionAddProductToShippingDocumentDialogComponent;
  @ViewChild('addProductPartiallyDialog')
  addProductPartiallyDialog: RemissionAddProductToShippingDocumentPartiallyDialogComponent;
  selectedFeatureDescription: string;
  toolTipOpened = [];
  tooltipMl = -10;
  tooltipArrowMl = 5;
  openedRemissionDialog = false;
  openedRemissionPartiallyDialog = false;
  isRemitted = false;

  private _product: RemissionProduct;
  constructor(
    private remissionService: RemissionService,
    private store: Store,
    private remissionHelper: RemissionHelperService,
    private cdr: ChangeDetectorRef,
    private errorService: ErrorService
  ) {}

  ngOnInit() {}

  openTooltip(index: number) {
    this.toolTipOpened = this.toolTipOpened.map((opened, i) => (opened = index === i ? true : false));
  }

  closeTooltip(index: number) {
    this.toolTipOpened[index] = false;
  }

  openRemitProductPartiallyDialog() {
    this.openedRemissionPartiallyDialog = true;
    this.detectChanges();
    setTimeout(() => {
      this.addProductPartiallyDialog.openDialog();
    }, 40);
  }

  openRemitProductDialog() {
    this.openedRemissionDialog = true;
    this.detectChanges();
    setTimeout(() => {
      this.addProductDialog.openDialog();
    }, 40);
  }

  closedDialog() {
    this.openedRemissionDialog = false;
  }

  closedDialogPartially() {
    this.openedRemissionPartiallyDialog = false;
  }

  remit() {
    if (this.product.remissionQuantity < 1) {
      setTimeout(() => {
        this.addProductDialog.stopLoading();
      }, 500);
      return;
    }
    const currentShippingDocument = this.store.selectSnapshot(RemissionSelectors.getRemissionShippingDocument);
    this.remissionService
      .addProductToShippingDocument({
        remissionProcessId: this.remissionProcess.id,
        remissionProductId: this.product.id,
        shippingDocumentId: currentShippingDocument.id,
        quantity: this.product.remissionQuantity,
        placementType: this.product.placementType,
        inStock: this.product.inStock,
      })
      .toPromise()
      .then((err) => {
        this.handleRemissionResponseErrors(err);
        this.remissionHelper.deleteRemissionListItem(this.product);
        this.openedRemissionDialog = false;
        this.removeProductFromView();

        this.updateShippingDocument.emit();
      })
      .catch((err) => {
        console.error(err);
        this.addProductDialog.stopLoading();
        this.addProductDialog.closeDialog();
      });
  }

  remitPartially(partialRemission: { quantity: number; placementType: string; predefinedRemissionQuantity: number }) {
    if (this.product.remissionQuantity < 1) {
      setTimeout(() => {
        this.addProductPartiallyDialog.stopLoading();
      }, 500);
      return;
    }
    const currentShippingDocument = this.store.selectSnapshot(RemissionSelectors.getRemissionShippingDocument);

    this.remissionService
      .addProductToShippingDocument({
        remissionProcessId: this.remissionProcess.id,
        remissionProductId: this.product.id,
        shippingDocumentId: currentShippingDocument.id,
        quantity: partialRemission.quantity,
        placementType: partialRemission.placementType,
        inStock: this.product.inStock,
        predefinedRemissionQuantity: partialRemission.predefinedRemissionQuantity,
      })
      .toPromise()
      .then((err) => {
        this.handleRemissionResponseErrors(err, true);
        if (partialRemission.quantity >= this.product.remissionQuantity) {
          this.remissionHelper.deleteRemissionListItem(this.product);
        } else {
          this.remissionHelper.updateRemissionListItem(partialRemission.quantity, this.product);
        }
        this.closedDialogPartially();
        this.removeProductFromView();

        this.updateShippingDocument.emit();
      })
      .catch((err) => {
        console.error(err);
        this.addProductPartiallyDialog.stopLoading();
        this.addProductPartiallyDialog.closeDialog();
      });
  }

  private removeProductFromView() {
    this.isRemitted = true;
  }

  handleRemissionResponseErrors(err: any, partial: boolean = false) {
    if (err.error) {
      console.error('addProductToShippingDocument error', err);
      const invalidProperties = err.errorReasons && Object.keys(err.errorReasons).length > 0 ? JSON.stringify(err.errorReasons) : undefined;
      this.errorService.addErrors(err.httpError ? err.httpError.code : 400, err.message, JSON.stringify(invalidProperties));
    }
    if (partial) {
      this.addProductPartiallyDialog.stopLoading();
      this.addProductPartiallyDialog.closeDialog();
    } else {
      this.addProductDialog.stopLoading();
      this.addProductDialog.closeDialog();
    }
  }

  isArray(obj) {
    return Array.isArray(obj);
  }

  getObjectKey(obj, index) {
    return Object.keys(obj)[index];
  }

  getObjectValue(obj, index) {
    return obj[Object.keys(obj)[index]];
  }

  detectChanges() {
    setTimeout(() => {
      if (this.cdr !== null && this.cdr !== undefined && !(this.cdr as ViewRef).destroyed) {
        this.cdr.detectChanges();
      }
    }, 0);
  }
}
