import { Product } from '../models/product.model';
import { isNullOrUndefined } from 'util';
import { ItemDTO } from '@swagger/cat';
import { Injectable } from '@angular/core';
import { PriceDTO } from '@cmf/trade-api';

@Injectable({ providedIn: 'root' })
export class ProductMapping {
  fromItemDTO(item: ItemDTO): Product {
    if (isNullOrUndefined(item)) {
      throw new Error('argument item:ItemDTO is null or undefined.');
    }

    let currency = '';
    let price = 0;

    let priceDto: PriceDTO;
    let ssc = '';
    let sscText = '';
    let storeStatusCode = 0;

    if (!!item.catalogAvailability) {
      priceDto = item.catalogAvailability.price;
      ssc = item.catalogAvailability.ssc;
      sscText = item.catalogAvailability.sscText;
      storeStatusCode = item.catalogAvailability.status;
    }

    if (!!priceDto && priceDto.value) {
      price = priceDto.value.value || price;
      currency = priceDto.value.currency || currency;
    }

    let itemsInStock = 0;

    if (Array.isArray(item.stockInfos)) {
      itemsInStock = item.stockInfos.reduce((aggr, si) => aggr + si.inStock, 0);
    }

    let assortment: string;
    if (item.shelfInfos) {
      assortment = item.shelfInfos[0].assortment ? item.shelfInfos[0].assortment : item.shelfInfos[0].label;
    }

    return {
      author: item.product.contributors,
      availability: !!item.catalogAvailability,
      currency,
      price,
      id: item.id,
      itemsInStock,
      err: '',
      category: assortment,
      icon: '',
      notAvailableReason: itemsInStock === 0 ? '' : '',
      publisher: item.product.manufacturer,
      recommandation: false,
      serial: item.product.serial,
      slogan: item.product.additionalName,
      title: item.product.name,
      type: item.product.formatDetail,
      typeIcon: item.product.format,
      location: item.product.productGroup,
      publicationDate: new Date(item.product.publicationDate),
      ean: item.product.ean,
      imageId: item.imageId,
      edition: item.product.edition,
      volume: item.product.volume,
      ssc,
      sscText,
      storeStatusCode: storeStatusCode,
    };
  }
}
