package org.exoplatform.cs.service.util;

import org.exoplatform.commons.utils.CommonsUtils;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.cs.dto.TicketDTO;
import org.exoplatform.cs.entity.SpaceEntity;
import org.exoplatform.cs.service.CSSpaceService;
import org.exoplatform.services.mail.MailService;
import org.exoplatform.services.mail.Message;
import org.exoplatform.social.core.identity.model.Profile;
import org.exoplatform.web.security.Token;
import org.exoplatform.web.security.security.CookieTokenService;
import org.gatein.common.logging.Logger;
import org.gatein.common.logging.LoggerFactory;
import org.gatein.wci.security.Credentials;

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


public class CustomerRateMailUtils {

    private static MailService mailService = PortalContainer.getInstance().getComponentInstanceOfType(MailService.class);
    private static CSSpaceService csSpaceService = PortalContainer.getInstance().getComponentInstanceOfType(CSSpaceService.class);
    private static CookieTokenService cookieTokenService = PortalContainer.getInstance().getComponentInstanceOfType(CookieTokenService.class);

    private static final Logger LOG = LoggerFactory.getLogger(CustomerRateMailUtils.class);


    public static void sendCustomerRateEmail(TicketDTO ticketDTO, SpaceEntity spaceEntity, Profile reciepentProfile,InputStream mailTemplate) {

        try {
            String language = csSpaceService.convertToDTO(spaceEntity).getLanguage().toLowerCase();
            Locale locale = new Locale(language);
            String mailFrom = "noreply@exoplatform.com";
            ResourceBundle resourceBundle = ResourceBundle.getBundle("locale.customer-space", locale, CustomerRateMailUtils.class.getClassLoader());
            String subject = resourceBundle.getString("cs.rate.mail.subject").replace("{0}",ticketDTO.getTitle());
            Message message = new Message();
            message.setFrom(mailFrom);
            message.setTo(reciepentProfile.getEmail());
            message.setSubject(subject);

            String ticketId = ticketDTO.getTicketId();

            Map<String,String> mailProperties = new HashMap<String,String>();
            Credentials credentials = new Credentials("csrate",ticketDTO.getId());
            String token = cookieTokenService.createToken(credentials);
            mailProperties.put("TICKET_NAME", ticketId);
            mailProperties.put("TICKET_URL", CommonsUtils.getCurrentDomain()+"/"+ CommonsUtils.getRestContextName() + "/customerspace/rate/setStatus?token="+token);
            mailProperties.put("FULLNAME", (String) reciepentProfile.getProperty(Profile.FULL_NAME));
            mailProperties.put("TITLE", resourceBundle.getString("cs.rate.mail.title"));
            mailProperties.put("RATEBTN", resourceBundle.getString("cs.rate.mail.ratebtn") + " " + ticketId );
            mailProperties.put("GREETING", resourceBundle.getString("cs.rate.mail.greeting"));
            mailProperties.put("MESSAGE", resourceBundle.getString("cs.rate.mail.message").replace("{0}",ticketId));
            mailProperties.put("SIGNATURE", resourceBundle.getString("cs.rate.mail.signature"));
            mailProperties.put("CUST_LOCALE", language);
            String emailBody = buildEmailBody(mailTemplate,mailProperties);
            message.setBody(emailBody);
            message.setMimeType("text/html");
            mailService.sendMessage(message);
            LOG.info("Sending mail about the customer Rate");
        } catch (Exception e) {
            LOG.error("Error while sending customer rate mail.", e);
        }
    }

    private static String buildEmailBody(InputStream mailInputStream,Map<String,String> mailProperties) throws Exception{
        StringBuilder stringBuilder = new StringBuilder();
        Scanner input = new Scanner(mailInputStream);
        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 = mailProperties.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry mailProperty = (Map.Entry)it.next();
            content = content.replaceAll("\\$\\{" + mailProperty.getKey() + "\\}", (String) mailProperty.getValue());
         }
        return content;
    }
}