package com.arms.api.issue.priority.strategy;

import com.arms.api.issue.priority.model.IssuePriorityDTO;
import com.arms.api.serverinfo.model.vo.ServerInfoVO;
import com.arms.api.serverinfo.service.ServerInfoService;
import com.arms.api.util.alm.JiraUtil;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.Priority;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Slf4j
@Component
@AllArgsConstructor
public class OnpremiseJiraIssuePriorityStrategy implements IssuePriorityStrategy {

    private final JiraUtil jiraUtil;

    private final ServerInfoService serverInfoService;

    @Override
    public List<IssuePriorityDTO> getIssuePriorityList(ServerInfoVO serverInfoVO) {

        try(JiraRestClient restClient = jiraUtil.createJiraOnPremiseCommunicator(serverInfoVO.getUri(),
                serverInfoVO.getUserId(),
                serverInfoService.getDecryptPasswordOrToken(serverInfoVO.getPasswordOrToken()))){

            Iterable<Priority> jiraPriorityList = restClient.getMetadataClient().getPriorities().claim();
            if (jiraPriorityList == null) {
                log.error("{}({}) 서버에 설정된 이슈 우선순위가 없습니다. 확인이 필요합니다.", serverInfoVO.getType(), serverInfoVO.getUri());
                return Collections.emptyList();
            }

            return StreamSupport.stream(jiraPriorityList.spliterator(), false)
                    .map(this::convertIssuePriorityDTO)
                    .collect(Collectors.toList());

        }catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    private IssuePriorityDTO convertIssuePriorityDTO(Priority priority) {
        IssuePriorityDTO issuePriorityDTO = new IssuePriorityDTO();
        issuePriorityDTO.setSelf(String.valueOf(priority.getSelf()));
        issuePriorityDTO.setId(String.valueOf(priority.getId()));
        issuePriorityDTO.setName(priority.getName());
        issuePriorityDTO.setDescription(priority.getDescription());

        return issuePriorityDTO;
    }
}
