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.RedmineApi;
import com.arms.api.util.alm.RedmineUtil;
import com.arms.api.util.errors.ErrorLogUtil;
import com.taskadapter.redmineapi.RedmineException;
import com.taskadapter.redmineapi.RedmineManager;
import com.taskadapter.redmineapi.bean.IssueStatus;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

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

@Component
@AllArgsConstructor
public class OnPremiseRedmineIssueStatusStrategy implements IssueStatusStrategy {

    private final RedmineUtil redmineUtil;

    private final RedmineApi redmineApi;

    private final ServerInfoService serverInfoService;

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

        RedmineManager redmineManager = redmineUtil.createRedmineOnPremiseCommunicator(serverInfoVO.getUri(),
                serverInfoService.getDecryptPasswordOrToken(serverInfoVO.getPasswordOrToken()));

        try {
            List<IssueStatus> redmineIssueStatusList = redmineManager.getIssueManager().getStatuses();

            List<IssueStatusVO> issueStatusList = redmineIssueStatusList.stream()
                    .map(issueStatus -> this.convertIssueStatusVO(issueStatus, serverInfoVO.getUri()))
                    .filter(Objects::nonNull)
                    .collect(toList());

            return issueStatusList;
        }
        catch (RedmineException 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(IssueStatus issueStatus, String serverUri) {
        String self = redmineUtil.checkServerInfoPath(serverUri) +
                redmineApi.replaceID(
                        redmineApi.getEndpoint().getIssuestatus(), String.valueOf(issueStatus.getId())
                );

        return IssueStatusVO.builder()
                .self(self)
                .id(issueStatus.getId().toString())
                .name(issueStatus.getName()).build();
    }
}
