import { Injectable } from '@angular/core';
import { Mapper } from './mapper';
import { RemissionProduct } from '../models/remission-product';
import { ReturnItemDTO } from '@swagger/remi';

@Injectable()
export class ReturnItemDtoToRemissionProductMapping implements Mapper<ReturnItemDTO, RemissionProduct> {
  get sourceName(): string {
    return 'ReturnItemDTO';
  }

  get targetName(): string {
    return 'RemissionProduct';
  }

  private getFeatures(assortment: string) {
    const featuresString = assortment && assortment.split('|');

    let features = [];
    if (featuresString) {
      features = featuresString.slice(1, featuresString.length).map((str, index) => {
        return {
          [str.split(';')[0]]: assortment.split('|')[index].split(';')[1] || assortment.split('|')[index],
        };
      });
    }

    const uniqueKeys = Array.from(new Set(features.map((feature) => Object.keys(feature)).reduce((acc, curr) => acc.concat(curr), [])));

    const result = uniqueKeys.map((key) => {
      return {
        [key]: features
          .map((feature) => {
            if (feature.hasOwnProperty(key)) {
              return feature[key];
            }
          })
          .filter((f) => !!f)
          .join(', ')
          .toString()
          .trim(),
      };
    });

    return result;
  }

  map(source: ReturnItemDTO): RemissionProduct {
    return {
      id: source.id,
      department: source.department,
      imageId: source.product.ean,
      contributors: source.product.contributors,
      name: source.product.name,
      format: source.product.format,
      formatDetail: source.product.formatDetail,
      ean: source.product.ean,
      price: source.retailPrice.value.value,
      currency: source.retailPrice.value.currency,
      productGroup: source.product.productGroup,
      productGroupName: '',
      inStock: null, // info retrieved separately
      remissionQuantity: source.predefinedReturnQuantity,
      remainingQuantity: source.remainingQuantityInStock,
      placementType: source.placementType,
      remissionReason: source.returnReason,
      edition: source.product.volume,
      isManuallyAdded: source.source && source.source === 'manually-added' ? true : false,
      catalogProductNumber: source.product.catalogProductNumber,
      features: this.getFeatures(source.assortment), // assortment (semicolon separiert ohne 'SO') z.B. "Wirtschaft|B"
      isResidual: source.descendantOf && source.descendantOf.enabled ? true : false || !!source.impediment,
      impediment: source.impediment,
    } as RemissionProduct;
  }
}
