package com.wishurgift.service.dto.transformer;

import com.wishurgift.persistence.entity.Wishlist;
import com.wishurgift.service.dto.WishlistDTO;
import com.wishurgift.service.dto.WishlistHeaderDTO;
import com.wishurgift.service.dto.WishlistSizeDTO;
import com.wishurgift.utils.Constant;

import java.util.ArrayList;
import java.util.List;

public class WishlistTransformer {

    public static WishlistDTO entityToDto(Wishlist entity) {
        if (entity == null) {
            return null;
        }

        WishlistDTO dto = new WishlistDTO();
        dto.setId(entity.getId());
        dto.setName(entity.getName());
        dto.setPublic(entity.isPublic());
        dto.setSize(entityToSizeDto(entity));
        dto.setElement(ElementTransformer.entityToDto(entity.getElements()));

        return dto;
    }

    public static List<WishlistDTO> entityToDto(List<Wishlist> entity) {
        if (entity == null) {
            return null;
        }

        List<WishlistDTO> dto = new ArrayList<>();
        entity.forEach(elt -> dto.add(entityToDto(elt)));
        return dto;
    }

    public static WishlistHeaderDTO entityToHeaderDto(Wishlist entity) {
        return entityToHeaderDto(entity, false);
    }

    public static List<WishlistHeaderDTO> entityToHeaderDto(List<Wishlist> entity) {
        return entityToHeaderDto(entity, false);
    }

    public static WishlistHeaderDTO entityToHeaderDto(Wishlist entity, boolean addUser) {
        if (entity == null) {
            return null;
        }

        WishlistHeaderDTO dto = new WishlistHeaderDTO();
        dto.setId(entity.getId());
        dto.setName(entity.getName());
        dto.setPublic(entity.isPublic());
        dto.setSize(entityToSizeDto(entity));
        if (addUser) {
            dto.setUser(UserTransformer.entityToLightDto(entity.getUser()));
        }

        return dto;
    }

    public static List<WishlistHeaderDTO> entityToHeaderDto(List<Wishlist> entity, boolean addUser) {
        if (entity == null) {
            return null;
        }

        List<WishlistHeaderDTO> dto = new ArrayList<>();
        entity.forEach(elt -> dto.add(entityToHeaderDto(elt, addUser)));
        return dto;
    }

    private static WishlistSizeDTO entityToSizeDto(Wishlist entity) {
        WishlistSizeDTO size = new WishlistSizeDTO();
        if (entity.getElements() != null) {
            long unbuy = entity.getElements().stream()
                    .map(elt -> Constant.Status.fromName(elt.getStatus()))
                    .filter(elt -> elt != Constant.Status.PURCHASED)
                    .count();
            size.setTotal(entity.getElements().size());
            size.setUnbuy(unbuy);
        }
        return size;
    }

}
