/*  
 *  Imixs-Workflow 
 *  
 *  Copyright (C) 2001-2020 Imixs Software Solutions GmbH,  
 *  http://www.imixs.com
 *  
 *  This program is free software; you can redistribute it and/or 
 *  modify it under the terms of the GNU General Public License 
 *  as published by the Free Software Foundation; either version 2 
 *  of the License, or (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
 *  General Public License for more details.
 *  
 *  You can receive a copy of the GNU General Public
 *  License at http://www.gnu.org/licenses/gpl.html
 *  
 *  Project: 
 *      https://www.imixs.org
 *      https://github.com/imixs/imixs-workflow
 *  
 *  Contributors:  
 *      Imixs Software Solutions GmbH - Project Management
 *      Ralph Soika - Software Developer
 */

package com.alexanderlogistics.api;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.logging.Logger;

import org.imixs.melman.CookieAuthenticator;
import org.imixs.melman.DocumentClient;
import org.imixs.melman.RestAPIException;
import org.imixs.workflow.ItemCollection;
import org.imixs.workflow.exceptions.QueryException;

import jakarta.annotation.Resource;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Cookie;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

/**
 * The api endpoint '/data' provides methods to read and post data via a access
 * token
 * 
 * @version 1.0
 * @author rsoika
 *
 */
@Path("/data")
@Stateless
public class DataRestService {

    @Context
    private HttpServletRequest servletRequest;

    @Context
    HttpServletResponse servletResponse;

    @Resource
    private SessionContext ctx;

    private static Logger logger = Logger.getLogger(DataRestService.class.getName());

    @GET
    @Path("/ping")
    public String ping() {
        logger.info("GET ping");
        return "ping: " + System.currentTimeMillis();
    }

    /**
     * Test method
     * 
     * @param workflowgroup
     * @param task
     * @return
     * @throws QueryException
     */
    @GET
    @Path("/report/{name}")
    @Produces({ MediaType.TEXT_HTML })
    public Response getReportData(@PathParam("name") String name, @QueryParam("token") String token)
            throws QueryException {

        logger.info("Report Name=" + name);
        String baseURI = servletRequest.getRequestURL().toString();

        baseURI = baseURI.substring(0, baseURI.indexOf("/data/report/" + name));
        baseURI = baseURI.replace("http://", "https://");
        logger.info("Base URL=" + baseURI);
        Client client = createClient(baseURI, token);

        if (client == null) {
            return Response.ok().status(Response.Status.FORBIDDEN).build();
        }
        // Specify the target URL
        String url = baseURI + "/report/" + name + ".html";
        WebTarget target = client.target(url);
        Response response = target.request().get();

        // Check the response status and process the response
        if (response.getStatus() == 200) {
            String result = response.readEntity(String.class);

            return Response.ok(result).build();
        }

        return Response.ok().status(Response.Status.BAD_REQUEST).build();
    }

    /**
     * creates a new Instance of a WorkflowClient.
     * <p>
     * In case the current request contains an authentication token we propagate
     * this token to the service.
     * <p>
     * The method tests the access. If it is not possible the method returns null.
     * 
     * @see DefaultAuthenicator
     * @return
     */
    protected Client createClient(String serviceAPI, String sessionID) {

        // Create a Cookie object with a name and a value
        Cookie cookie = new Cookie.Builder("JSESSIONID")
                .value(sessionID)
                .path("/")
                // .domain("domain.com")
                .build();

        DocumentClient client = new DocumentClient(serviceAPI.trim());
        CookieAuthenticator aut = new CookieAuthenticator(cookie);
        client.registerClientRequestFilter(aut);

        Client rsClient = client.newClient();
        rsClient.register(aut);

        // Test access
        String url = client.getBaseURI() + "documents/";
        WebTarget target = rsClient.target(url);
        Response response = target.request().get();
        if (response.getStatus() == 200 || response.getStatus() == 308) {
            String result = response.readEntity(String.class);
            if (result.contains("j_password")) {
                logger.info("Request failed - login failed");
                return null;
            }
            logger.info("login successful");
        } else {
            logger.info("Request failed with status code: " + response.getStatus());
            return null;
        }

        return rsClient;
    }

    /**
     * Searches a report by name
     * 
     * @param name
     * @return
     * @throws UnsupportedEncodingException
     * @throws RestAPIException
     */
    protected ItemCollection findReport(DocumentClient client, String name)
            throws RestAPIException, UnsupportedEncodingException {
        String query = "(type:\"ReportEntity\" AND txtname:\"" + name + "\")";
        List<ItemCollection> result = client.searchDocuments(query);

        if (result != null && result.size() > 0) {
            // return first match
            return result.get(0);
        }

        return null;
    }

}
