/*
 * Copyright (C) 2003-2015 eXo Platform SAS.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.exoplatform.cs.integration.notification;

import org.exoplatform.calendar.service.CalendarService;
import org.exoplatform.calendar.service.CalendarSetting;
import org.exoplatform.commons.api.notification.NotificationContext;
import org.exoplatform.commons.api.notification.annotation.TemplateConfig;
import org.exoplatform.commons.api.notification.annotation.TemplateConfigs;
import org.exoplatform.commons.api.notification.channel.template.AbstractTemplateBuilder;
import org.exoplatform.commons.api.notification.channel.template.TemplateProvider;
import org.exoplatform.commons.api.notification.model.MessageInfo;
import org.exoplatform.commons.api.notification.model.NotificationInfo;
import org.exoplatform.commons.api.notification.model.PluginKey;
import org.exoplatform.commons.api.notification.service.template.TemplateContext;
import org.exoplatform.commons.notification.template.DigestTemplate.ElementType;
import org.exoplatform.commons.notification.template.TemplateUtils;
import org.exoplatform.commons.utils.CommonsUtils;
import org.exoplatform.commons.utils.HTMLEntityEncoder;
import org.exoplatform.container.xml.InitParams;
import org.exoplatform.cs.service.util.CSUtils;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.social.core.identity.model.Identity;
import org.exoplatform.social.core.identity.model.Profile;
import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider;
import org.exoplatform.social.core.manager.IdentityManager;
import org.exoplatform.social.notification.LinkProviderUtils;
import org.gatein.common.text.EntityEncoder;

import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@TemplateConfigs(templates = {

    @TemplateConfig(pluginId = CSReminderPlugin.ID, template = "war:/notification/templates/mail/CSReminderPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSStatusChangedNotificationPlugin.ID, template = "war:/notification/templates/mail/CSStatusChangedNotificationPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSTicketAssignedNotificationPlugin.ID, template = "war:/notification/templates/mail/CSTicketAssignedNotificationPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSTicketAssignedToMeNotificationPlugin.ID, template = "war:/notification/templates/mail/CSTicketAssignedToMeNotificationPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSTicketClosedNotificationPlugin.ID, template = "war:/notification/templates/mail/CSTicketClosedNotificationPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSSubscriptionExpiredPlugin.ID, template = "war:/notification/templates/mail/CSSubscriptionExpiredPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSSubscriptionReminderPlugin.ID, template = "war:/notification/templates/mail/CSSubscriptionReminderPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSPrivatePostPlugin.ID, template = "war:/notification/templates/mail/CSPrivatePostPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSSLAReminderPlugin.ID, template = "war:/notification/templates/mail/CSSLAReminderPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSAddPostPlugin.ID, template = "war:/notification/templates/mail/CSAddPostPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSRatePlugin.ID, template = "war:/notification/templates/mail/CSRatePlugin.gtmpl"),
    @TemplateConfig(pluginId = CSAnnouncementPlugin.ID, template = "war:/notification/templates/mail/CSAnnouncementPlugin.gtmpl"),
    @TemplateConfig(pluginId = CSSpaceEditionPlugin.ID, template = "war:/notification/templates/mail/CSSpaceEditionPlugin.gtmpl")
})
public class MailTemplateProvider extends TemplateProvider {
  //--- Use a dedicated DateFormatter to handle date pattern coming from underlying levels : Wed Mar 15 01:00:00 CET 2017
  // --- Create formatter
  protected DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
  //protected DateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
  protected static Log log = ExoLogger.getLogger(MailTemplateProvider.class);

  public MailTemplateProvider(InitParams initParams) {
    super(initParams);

    this.templateBuilders.put(PluginKey.key(CSReminderPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSStatusChangedNotificationPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSTicketAssignedNotificationPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSTicketAssignedToMeNotificationPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSTicketClosedNotificationPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSSubscriptionExpiredPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSSubscriptionReminderPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSPrivatePostPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSSLAReminderPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSAddPostPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSRatePlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSAnnouncementPlugin.ID), new TemplateBuilder());
    this.templateBuilders.put(PluginKey.key(CSSpaceEditionPlugin.ID), new TemplateBuilder());
  }
  
  private class TemplateBuilder extends AbstractTemplateBuilder {
    @Override
    protected MessageInfo makeMessage(NotificationContext ctx) {

      EntityEncoder encoder = HTMLEntityEncoder.getInstance();
      
      NotificationInfo notification = ctx.getNotificationInfo();
      String language = getLanguage(notification);
      log.info("Prepare Mail notif for "+ notification.getKey().getId());
      String creator = notification.getValueOwnerParameter(NotificationUtils.CREATOR);
      String ticketUrl = notification.getValueOwnerParameter(NotificationUtils.TICKET_URL);
      String userName = notification.getValueOwnerParameter(NotificationUtils.USER_NAME);
      String ticketId = notification.getValueOwnerParameter(NotificationUtils.TICKET_ID);
      String ticketTitle = notification.getValueOwnerParameter(NotificationUtils.TICKET_TITLE);
      String ticketStatus = notification.getValueOwnerParameter(NotificationUtils.TICKET_STATUS);
      String rateType = notification.getValueOwnerParameter(NotificationUtils.RATE_TYPE);
      String ratedFrom = notification.getValueOwnerParameter(NotificationUtils.RATED_FROM);
      String assignee = notification.getValueOwnerParameter(NotificationUtils.ASSIGNEE);
      String oldValue = notification.getValueOwnerParameter(NotificationUtils.OLD_VALUE);
      String period = notification.getValueOwnerParameter(NotificationUtils.PERIOD);
      String spaceId = notification.getValueOwnerParameter(NotificationUtils.SPACE_ID);
      String spaceName = notification.getValueOwnerParameter(NotificationUtils.SPACE_NAME);
      String spaceUrl = notification.getValueOwnerParameter(NotificationUtils.SPACE_URL);
      String endDate = notification.getValueOwnerParameter(NotificationUtils.END_DATE);
      String post = notification.getValueOwnerParameter(NotificationUtils.POST);
      String days = notification.getValueOwnerParameter(NotificationUtils.DAYS);
      String hours = notification.getValueOwnerParameter(NotificationUtils.HOURS);
      String minutes = notification.getValueOwnerParameter(NotificationUtils.MINUTES);
      String actionName = notification.getValueOwnerParameter(NotificationUtils.ACTION_NAME.getKey());

      TemplateContext templateContext = new TemplateContext(notification.getKey().getId(), language);
      if(actionName!=null){
        templateContext.put("ACTION_NAME", actionName);
      }
      IdentityManager identityManager = CommonsUtils.getService(IdentityManager.class);
      Identity author = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, creator, true);
      Profile profile = author.getProfile();
      //creator
      templateContext.put("USER", encoder.encode(profile.getFullName()));
      templateContext.put("AVATAR", LinkProviderUtils.getUserAvatarUrl(profile));
      templateContext.put("PROFILE_URL", LinkProviderUtils.getRedirectUrl("user", author.getRemoteId()));
      //receiver
      Identity receiver = CommonsUtils.getService(IdentityManager.class).getOrCreateIdentity(OrganizationIdentityProvider.NAME, notification.getTo(), true);
      templateContext.put("FIRST_NAME", encoder.encode(receiver.getProfile().getProperty(Profile.FIRST_NAME).toString()));
      //
        if(ticketUrl!=null) {
            templateContext.put("TICKET_URL", ticketUrl);
        }

      if(userName!=null) {
        Identity id=identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userName, false);
        templateContext.put("USER_NAME", id.getProfile().getFullName());
      }

      if(assignee!=null) {
        Identity id=identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, assignee, false);
        templateContext.put("ASSIGNEE", id.getProfile().getFullName());
      }

      if(ticketId!=null) {
        templateContext.put("TICKET_ID", ticketId);
      }

      if(ticketTitle!=null) {
        templateContext.put("TICKET_TITLE", ticketTitle);
      }

      if(ticketStatus!=null) {
        templateContext.put("TICKET_STATUS", ticketStatus);
      }

      if(rateType!=null) {
        templateContext.put("RATE_TYPE", rateType);
      }

      if(ratedFrom!=null) {
        templateContext.put("RATED_FROM", ratedFrom);
      }

      if(oldValue!=null) {
        templateContext.put("OLD_VALUE", oldValue);
      }

      if(period!=null) {
        templateContext.put("PERIOD", period);
      }

      if(spaceId!=null) {
        templateContext.put("SPACE_ID", spaceId);
      }

      if(spaceName!=null) {
        templateContext.put("SPACE_NAME", spaceName);
      }

      if(spaceUrl!=null) {
        templateContext.put("SPACE_URL", spaceUrl);
      }


      if (endDate != null && !endDate.equals("")) {
        templateContext.put("END_DATE", CSUtils.formatDate(endDate, CSUtils.getUserTimezone(notification.getTo())));
      }

      if (post != null) {
        templateContext.put("POST", post);
      }


      if (hours != null) {
        templateContext.put("HOURS", hours);
      }


      if (days != null) {
        templateContext.put("DAYS", days);
      }


      if (minutes != null) {
        templateContext.put("MINUTES", minutes);
      }




      templateContext.put("FOOTER_LINK", LinkProviderUtils.getRedirectUrl("notification_settings", receiver.getRemoteId()));
      String subject = TemplateUtils.processSubject(templateContext);

      String body = TemplateUtils.processGroovy(templateContext);
      //binding the exception throws by processing template
      ctx.setException(templateContext.getException());
      MessageInfo messageInfo = new MessageInfo();
      return messageInfo.subject(subject).body(body).end();
    }

    @Override
    protected boolean makeDigest(NotificationContext ctx, Writer writer) {
      EntityEncoder encoder = HTMLEntityEncoder.getInstance();
      
      List<NotificationInfo> notifications = ctx.getNotificationInfos();
      NotificationInfo first = notifications.get(0);

      String language = getLanguage(first);
      TemplateContext templateContext = new TemplateContext(first.getKey().getId(), language);
      //
      Identity receiver = CommonsUtils.getService(IdentityManager.class).getOrCreateIdentity(OrganizationIdentityProvider.NAME, first.getTo(), true);
      templateContext.put("FIRST_NAME", encoder.encode(receiver.getProfile().getProperty(Profile.FIRST_NAME).toString()));
      templateContext.put("FOOTER_LINK", LinkProviderUtils.getRedirectUrl("notification_settings", receiver.getRemoteId()));
      
      try {
        writer.append(buildDigestMsg(notifications, templateContext));
      } catch (IOException e) {
        ctx.setException(e);
        return false;
      }
      return true;
    }

    protected String buildDigestMsg(List<NotificationInfo> notifications, TemplateContext templateContext) {
      EntityEncoder encoder = HTMLEntityEncoder.getInstance();
      
      Map<String, List<NotificationInfo>> map = new HashMap<String, List<NotificationInfo>>();
      for (NotificationInfo notif : notifications) {
        String activityID = notif.getValueOwnerParameter(NotificationUtils.ACTIVITY_ID);
        List<NotificationInfo> tmp = map.get(activityID);
        if (tmp == null) {
          tmp = new LinkedList<NotificationInfo>();
          map.put(activityID, tmp);
        }
        tmp.add(notif);
      }
      
      StringBuilder sb = new StringBuilder();
      for (String activityID : map.keySet()) {
        List<NotificationInfo> notifs = map.get(activityID);
        NotificationInfo first = notifs.get(0);
        String ticketUrl = first.getValueOwnerParameter(NotificationUtils.TICKET_URL);
        if (notifs.size() == 1) {
          templateContext.digestType(ElementType.DIGEST_ONE.getValue());
        } else {
          templateContext.digestType(ElementType.DIGEST_MORE.getValue());
        }
        sb.append("<li style=\"margin:0 0 13px 14px;font-size:13px;line-height:18px;font-family:HelveticaNeue,Helvetica,Arial,sans-serif\"><div style=\"color: #333;\">");
        String digester = TemplateUtils.processDigest(templateContext);
        sb.append(digester);
        sb.append("</div></li>");
      }
      return sb.toString();
    }
  }


  public static String getExcerpt(String str, int len) {
    if (str == null) {
      return "";
    } else if (str.length() > len) {
      str = str.substring(0, len);
      int lastSpace = str.lastIndexOf(" ");
      return ((lastSpace > 0) ? str.substring(0, lastSpace) : str) + "...";
    } else {
      return str;      
    }
  }


  protected String getDate(String date, String userName) {
    if (date != null) {
      Date date_ = new Date(Long.parseLong(date));
      return org.exoplatform.cs.integration.notification.TemplateUtils.format(date_,getUserTimezone(userName));
    } else {
      return "";
    }
  }


  public TimeZone getUserTimezone(String username) {
    try {
      CalendarService calService=  CommonsUtils.getService(CalendarService.class);
      CalendarSetting setting = calService.getCalendarSetting(username);
      return TimeZone.getTimeZone(setting.getTimeZone());
    } catch (Exception e) {
      log.error("Can't retrieve timezone", e);
    }
    return null;
  }

}
