package com.qqchen.deploy.backend.deploy.service.impl;

import com.qqchen.deploy.backend.deploy.converter.ApplicationConverter;
import com.qqchen.deploy.backend.deploy.converter.ProjectGroupConverter;
import com.qqchen.deploy.backend.deploy.dto.ApplicationDTO;
import com.qqchen.deploy.backend.deploy.dto.DevelopmentLanguageTypeDTO;
import com.qqchen.deploy.backend.deploy.entity.Application;
import com.qqchen.deploy.backend.deploy.entity.ProjectGroup;
import com.qqchen.deploy.backend.deploy.enums.DevelopmentLanguageTypeEnum;
import com.qqchen.deploy.backend.deploy.query.ApplicationQuery;
import com.qqchen.deploy.backend.deploy.repository.IProjectGroupRepository;
import com.qqchen.deploy.backend.deploy.service.IApplicationService;
import com.qqchen.deploy.backend.framework.service.impl.BaseServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

@Service
public class ApplicationServiceImpl extends BaseServiceImpl<Application, ApplicationDTO, ApplicationQuery, Long> implements IApplicationService {


    @Resource
    private IProjectGroupRepository projectGroupRepository;

    @Resource
    private ProjectGroupConverter projectGroupConverter;

    public Page<ApplicationDTO> page(ApplicationQuery query) {
        Page<ApplicationDTO> page = super.page(query);
        List<ApplicationDTO> result = page.getContent().stream().peek(application -> {
            Optional<ProjectGroup> projectGroupOptional = projectGroupRepository.findById(application.getProjectGroupId());
            projectGroupOptional.ifPresent(projectGroup -> application.setProjectGroup(projectGroupConverter.toDto(projectGroup)));
        }).collect(toList());
        return new PageImpl<>(result, page.getPageable(), page.getTotalElements());
    }

    @Override
    public List<DevelopmentLanguageTypeDTO> getAllDevelopmentLanguageTypes() {
        List<DevelopmentLanguageTypeDTO> result = new ArrayList<>();
        Arrays.stream(DevelopmentLanguageTypeEnum.values()).forEach(developmentLanguageTypeEnum -> {
            DevelopmentLanguageTypeDTO dto = new DevelopmentLanguageTypeDTO();
            dto.setCode(developmentLanguageTypeEnum.name());
            dto.setName(developmentLanguageTypeEnum.getCode());
            result.add(dto);
        });
        return result;
    }

} 