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

import com.arms.api.issue.status.model.vo.CloudJiraByIssueTypeIssueStatusVO;
import com.arms.api.issue.status.model.vo.IssueStatusVO;
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.Status;
import io.atlassian.util.concurrent.Promise;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

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

@Component
@AllArgsConstructor
public class OnPremiseJiraIssueStatusStrategy implements IssueStatusStrategy {

    private final JiraUtil jiraUtil;

    private final ServerInfoService serverInfoService;


    @Override
    public List<IssueStatusVO> getIssueStatusList(ServerInfoVO serverInfoVO) {

        try(JiraRestClient restClient = jiraUtil.createJiraOnPremiseCommunicator(serverInfoVO.getUri(),
                serverInfoVO.getUserId(),
                serverInfoService.getDecryptPasswordOrToken(serverInfoVO.getPasswordOrToken()))) {
            Promise<Iterable<Status>> statusesPromise = restClient.getMetadataClient().getStatuses();
            Iterable<Status> statuses = statusesPromise.claim();

            return StreamSupport.stream(statuses.spliterator(), false)
                    .map(this::convertIssueStatusVO)
                    .collect(Collectors.toList());
        }
        catch (Exception e) {
            String errorMessage =  ErrorLogUtil.exceptionLoggingAndReturn(e, this.getClass().getName(),
                    String.format("%s[%s] :: getIssueStatusList Error", serverInfoVO.getType(), serverInfoVO.getUri()));
            throw new IllegalArgumentException(errorMessage);
        }
    }

    @Override
    public List<CloudJiraByIssueTypeIssueStatusVO> getIssueStatusListByProject(ServerInfoVO serverInfoVO, String projectId) {
        return null;
    }

    private IssueStatusVO convertIssueStatusVO(Status issueStatus) {
        return IssueStatusVO.builder()
                .self(issueStatus.getSelf().toString())
                .id(issueStatus.getId().toString())
                .name(issueStatus.getName())
                .description(issueStatus.getDescription()).build();
    }
}
