package org.exoplatform.cs.rest;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.exoplatform.commons.api.notification.NotificationContext;
import org.exoplatform.commons.api.notification.model.PluginKey;
import org.exoplatform.commons.notification.impl.NotificationContextImpl;
import org.exoplatform.commons.utils.CommonsUtils;
import org.exoplatform.cs.dto.TicketDTO;
import org.exoplatform.cs.integration.notification.CSRatePlugin;
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.gatein.wci.security.Credentials;
import io.swagger.annotations.*;
import org.exoplatform.web.security.security.CookieTokenService;

import java.io.InputStream;
import java.util.*;

@Path("/customerspace/rate")
@Api(value = "/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")
    @ApiOperation(value = "Set Support Rate Status", httpMethod = "GET", response = Response.class, notes = "set rate status")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Request fulfilled"),
            @ApiResponse(code = 400, message = "Invalid query input"),
            @ApiResponse(code = 403, message = "Unauthorized operation"),
            @ApiResponse(code = 500, message = "Internal server error")})
    public Response setRateStatus(@ApiParam(value = "Token", required = true) @QueryParam("token") String token,
                                  @ApiParam(value = "Status", required = true) @QueryParam("status") boolean status,
                                  @ApiParam(value = "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;
    }

}