package com.collabnet.ctf.events.custom.events;

import com.collabnet.ce.soap60.webservices.ClientSoapStubFactory;
import com.collabnet.ce.soap60.webservices.tracker.ITrackerAppSoap;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.vasoftware.sf.common.logger.Logger;
import com.vasoftware.sf.events.EventHandler60;

import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.Date;

public class NewProjectCreationEventListener extends EventHandler60 {

    private static final Logger logger = Logger.getLogger(NewProjectCreationEventListener.class);

    private static final ObjectMapper om = new ObjectMapper();
    private static final ObjectWriter trackerEntityRequestWriter = om.writerFor(TrackerEntityRequest.class);

    @Override
    public void processEvent() throws Exception {
        createTemplateTracker(getEventContext().getProjectId());
    }

    /**
     * Creates temlate tracker via REST
     *
     * @param projectId
     */
    private void createTemplateTracker(String projectId) {
        try (
            Response response = RestClient.CTF.getBaseTarget()
                    .path("/ctfrest/tracker/v1/projects/" + projectId + "/trackers")
                    .request(MediaType.APPLICATION_JSON)
                    .header(HttpHeaders.AUTHORIZATION, "Bearer " + getSessionKey())
                    .post(Entity.json(
                            trackerEntityRequestWriter.writeValueAsString(getTrackerEntityRequest(projectId))));
        ) {
            if (response.getStatus() != 200) {
                throw new RuntimeException("Unable to create template tracker");
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Unable to create template tracker", e);
        }
    }

    /**
     * Creates REST tracker entity with randomized values
     *
     * @param projectId
     * @return
     */
    private TrackerEntityRequest getTrackerEntityRequest(String projectId) {
        Date currentTime = new Date();
        return new TrackerEntityRequest(
                "tracker" + currentTime.getTime(),
                "tracker title" + currentTime.getTime(),
                "Description : A template tracker to be created in a new project",
                "icon_01.png",
                getTrackerUnitId(projectId),
                true);
    }

    /**
     * Uses SOAP to get the tracker Unit ID for creating a tracker
     *
     * @param projectId
     * @return Tracker unit id
     */
    private String getTrackerUnitId(String projectId) {
        ITrackerAppSoap trackerClient = (ITrackerAppSoap) ClientSoapStubFactory.getSoapStub(ITrackerAppSoap.class,
                Configuration.getEndPointBaseUri());
        try {
            return trackerClient.getUnitsByProject(getSessionKey(), projectId).getDataRows()[0].getId();
        } catch (Exception e) {
            logger.error("Unable to get tracker unit id", e);
            throw new RuntimeException("Unable to get tracker unit id", e);
        }
    }
}
