package org.exoplatform.cs.rest;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.gatein.wci.security.Credentials;

import org.exoplatform.commons.utils.CommonsUtils;
import org.exoplatform.cs.dto.TicketDTO;
import org.exoplatform.cs.service.TicketService;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.rest.resource.ResourceContainer;
import org.exoplatform.web.security.security.CookieTokenService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;

@Path("/customerspace/rate")
@Tag(name = "/customerspace/rate")
public class CustomerRateRest implements ResourceContainer {

    private TicketService ticketService;
    private CookieTokenService cookieTokenService;

    private static final Log LOG =
            ExoLogger.getLogger(CustomerRateRest.class);

    public CustomerRateRest(TicketService ticketService, CookieTokenService cookieTokenService) {
        this.ticketService = ticketService;
        this.cookieTokenService = cookieTokenService;
    }

    @GET
    @Produces(MediaType.TEXT_HTML)
    @Path("setStatus")
    @Operation(description = "Set Support Rate Status", method = "GET", summary = "set rate status")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Request fulfilled"),
            @ApiResponse(responseCode = "400", description = "Invalid query input"),
            @ApiResponse(responseCode = "403", description = "Unauthorized operation"),
            @ApiResponse(responseCode = "500", description = "Internal server error")})
    public Response setRateStatus(@Parameter(description = "Token", required = true) @QueryParam("token") String token,
                                  @Parameter(description = "Status", required = true) @QueryParam("status") boolean status,
                                  @Parameter(description = "Language", required = true) @QueryParam("lang") String lang) {

        if( token == null || token.trim().isEmpty()){
            return Response.status(400).build();
        }
        if(lang == null || lang.trim().isEmpty() || (! lang.equals("en") && ! lang.equals("fr"))){
            lang = "en";
        }
        Credentials credentials;
        TicketDTO ticketDTO;
        try {
            credentials = cookieTokenService.validateToken(token, true);
            if (credentials == null) {
                LOG.warn("Unauthorized token with ID="+token);
                return Response.status(403).build();
            }
            ticketDTO = ticketService.findById(credentials.getPassword());
            ticketDTO.setCustomerSatisfied(status);
            ticketService.updateTicketSatisfaction(ticketDTO, ticketDTO.getCreatorId());
        } catch (Exception e) {
            LOG.error("Error while setting Ticket Rate Status", e);
            return Response.status(500).build();
        }
        InputStream pageTemplate = this.getClass().getClassLoader().getResourceAsStream("conf/portal/thankyourforrating.html");
        Map<String,String> pageProperties = new HashMap<>();
        Locale locale = new Locale(lang);
        ResourceBundle resourceBundle = ResourceBundle.getBundle("locale.customer-space", locale, CustomerRateRest.class.getClassLoader());
        pageProperties.put("THANK_TITLE",resourceBundle.getString("cs.rate.thank.title"));
        pageProperties.put("REDIRECTION_MSG",resourceBundle.getString("cs.rate.thank.redirection").replace("{0}",ticketDTO.getTicketId()));
        pageProperties.put("TICKET_URL",CommonsUtils.getCurrentDomain() + ticketDTO.getLink());
        pageProperties.put("REDIRECT_BTN",resourceBundle.getString("cs.rate.thank.redirectbtn"));
        pageProperties.put("THANK_REASON",resourceBundle.getString("cs.rate.thank.reason"));
        String content = buildHtmlBody(pageTemplate,pageProperties);
        ticketService.notifyCustomerRate(ticketDTO,null,true);
        return Response.ok(content).header("refresh","5;url="+ CommonsUtils.getCurrentDomain() + ticketDTO.getLink()).build();
    }


    private static String buildHtmlBody(InputStream inputStream, Map<String,String> pageProperties){
        StringBuilder stringBuilder = new StringBuilder();
        Scanner input = new Scanner(inputStream);
        String line;

        while (input.hasNext()) {
            line = input.nextLine();
            if (stringBuilder.toString().length() > 0) {
                stringBuilder.append("\n");
            }
            stringBuilder.append(line);
        }

        String content = stringBuilder.toString();
        Iterator it = pageProperties.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry mailProperty = (Map.Entry)it.next();
            content = content.replaceAll("\\$\\{" + mailProperty.getKey() + "\\}", (String) mailProperty.getValue());
        }
        return content;
    }

}