package io.delphiplatform.api.v3.rdb.service;

import com.google.common.collect.ImmutableMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import io.delphiplatform.api.v3.model.shazam.ShazamChart;
import io.delphiplatform.api.v3.rdb.entity.CommonJpaPropertyNames;
import io.delphiplatform.api.v3.rdb.entity.shazam.ShazamChartEntity;
import io.delphiplatform.api.v3.rdb.repository.ShazamChartRepository;
import io.delphiplatform.api.v3.rdb.service.dto.JpaPropertyPath;
import io.delphiplatform.api.v3.rdb.service.specification.SpecificationProvider;
import io.delphiplatform.api.v3.view.util.Params;

import static io.delphiplatform.api.v3.rdb.entity.CommonJpaPropertyNames.CHART_ID;
import static io.delphiplatform.api.v3.rdb.entity.CommonJpaPropertyNames.COUNTRY_CODE;
import static io.delphiplatform.api.v3.rdb.entity.CommonJpaPropertyNames.SHAZAM_CITY_ID;

@Service
@Transactional(readOnly = true)
public class ShazamChartService extends EntityService<ShazamChartEntity> {

    private static final ImmutableMap<String, String> SORT_BY_TO_ENTITY_FIELD_MAP =
        ImmutableMap.<String, String>builder()
            .put("city_id", "shazam_city_shazam_city_id")
            .put("country_code", "region_region_id")
            .put("city_name", "shazam_city_city_name")
            .build();

    private final SpecificationProvider<ShazamChartEntity> specificationProvider;

    @Autowired
    public ShazamChartService(ShazamChartRepository repository,
        SpecificationProvider<ShazamChartEntity> specificationProvider) {
        super(repository, SORT_BY_TO_ENTITY_FIELD_MAP);
        this.specificationProvider = specificationProvider;
    }

    public List<ShazamChart> getShazamCharts(Params params) {
        Set<JpaPropertyPath> fetches = Set.of(JpaPropertyPath.ofJoin(CommonJpaPropertyNames.SHAZAM_CITY),
            JpaPropertyPath.ofJoin(CommonJpaPropertyNames.REGION));
        Specification<ShazamChartEntity> spec = and(Arrays.asList(
            specificationProvider.multiValueSpec(CHART_ID, params.getChartId()),
            specificationProvider
                .multiValueSpec(SHAZAM_CITY_ID, params.getCityCode(), List.of(CommonJpaPropertyNames.SHAZAM_CITY)),
            specificationProvider
                .multiValueSpec(COUNTRY_CODE, params.getCountryCode(), List.of(CommonJpaPropertyNames.REGION)),
            specificationProvider.fetchesSpecOfPaths(fetches)
        ));

        List<ShazamChartEntity> entities = find(spec, getPageRequestSortByToCamelCase(params));

        return entities.stream().map(ShazamChart::of).collect(Collectors.toList());
    }

}
