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

import com.arms.api.issue.resolution.model.IssueResolutionData;
import com.arms.api.serverinfo.model.vo.ServerInfoVO;
import com.arms.api.serverinfo.service.ServerInfoService;
import com.arms.api.util.alm.JiraUtil;
import com.arms.api.util.errors.ErrorLogUtil;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.Resolution;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

@Component
@AllArgsConstructor
@Slf4j
public class OnPremiseJiraIssueResolutionStrategy implements IssueResolutionStrategy {

    private final JiraUtil jiraUtil;

    private final ServerInfoService serverInfoService;


    @Override
    public List<IssueResolutionData> getIssueResolutionList(ServerInfoVO serverInfoVO) {

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

            Iterable<Resolution> 온프레미스_이슈_해결책_목록 = restClient.getMetadataClient().getResolutions().claim();

            if (온프레미스_이슈_해결책_목록 == null) {
                log.error("온프레미스 지라( {} ) 서버에 설정된 이슈 해결책이 없습니다. 서버 정보 확인이 필요합니다.", serverInfoVO.getUri());
                return null;
            }

            List<IssueResolutionData> 반환할_이슈_해결책_목록 = StreamSupport.stream(온프레미스_이슈_해결책_목록.spliterator(), false)
                    .map(온프레미스_이슈_해결책 -> {
                        IssueResolutionData 반환할_이슈_해결책 = new IssueResolutionData();

                        반환할_이슈_해결책.setSelf(온프레미스_이슈_해결책.getSelf().toString());
                        반환할_이슈_해결책.setId(온프레미스_이슈_해결책.getId().toString());
                        반환할_이슈_해결책.setName(온프레미스_이슈_해결책.getName());
                        반환할_이슈_해결책.setDescription(온프레미스_이슈_해결책.getDescription());

                        return 반환할_이슈_해결책;
                    })
                    .collect(Collectors.toList());

            return 반환할_이슈_해결책_목록;
        }
        catch (Exception e) {
            String 에러로그 = ErrorLogUtil.exceptionLoggingAndReturn(e, this.getClass().getName(), "이슈해결책_목록_가져오기");
            throw new IllegalArgumentException(에러로그);
        }
    }
}
