/*
 * Copyright (C) 2003-2019 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.commons.api.notification.NotificationContext;
import org.exoplatform.commons.api.notification.model.ArgumentLiteral;
import org.exoplatform.commons.api.notification.model.NotificationInfo;
import org.exoplatform.commons.api.notification.plugin.BaseNotificationPlugin;
import org.exoplatform.commons.utils.CommonsUtils;
import org.exoplatform.container.xml.InitParams;
import org.exoplatform.cs.dto.TicketDTO;
import org.exoplatform.cs.service.util.CSUtils;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.organization.User;
import org.exoplatform.social.core.space.model.Space;
import org.exoplatform.social.core.space.spi.SpaceService;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;


public class CSRatePlugin extends BaseNotificationPlugin {

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

  public final static String ID = "CSRatePlugin";


  public final static ArgumentLiteral<TicketDTO> TICKET = new ArgumentLiteral<TicketDTO>(TicketDTO.class, "ticket");
  public final static ArgumentLiteral<String> RATER_USERNAME = new ArgumentLiteral<String>(String.class, "raterUsername");
  public final static ArgumentLiteral<Boolean> IS_RATED_FROM_MAIL = new ArgumentLiteral<Boolean>(Boolean.class, "isRatedFromMail");




  SpaceService spaceService;

  public CSRatePlugin(InitParams initParams, SpaceService spaceService) {

    super(initParams);
    this.spaceService = spaceService;

  }



  @Override

  public String getId() {

    return ID;

  }



  @Override

  public boolean isValid(NotificationContext ctx) {

    return true;

  }




  @Override

  protected NotificationInfo makeNotification(NotificationContext ctx) {

    TicketDTO ticket = ctx.value(TICKET);
    Boolean isRatedFromMail = ctx.value(IS_RATED_FROM_MAIL);
    String raterUsername = ctx.value(RATER_USERNAME);
    Set<String> receivers = new HashSet<String>();
    List<User> users = CSUtils.getInternalSupportMembers();
    if (users != null && users.size() > 0) {
      for (User user : users) {
        receivers.add(user.getUserName());
      }
    } else if (ticket.getAssignee() != null) {
      receivers.add(ticket.getAssignee());
    }
    StringBuilder activityId = new StringBuilder("support");
    activityId.append("-").append(ticket.getId());
    String ticketUrl = CommonsUtils.getCurrentDomain()+ticket.getLink();
    String ticketId = ticket.getTicketId();
    String ticketTitle = ticket.getTitle();
    Space space = null;
    try {
      space = spaceService.getSpaceByGroupId(ticket.getSpaceGroupId());
    } catch (Exception e) {
      LOG.error("Could not get Space with th group Id {}", ticket.getSpaceGroupId(), e);
    }
    Boolean rate = ticket.getCustomerSatisfied();
    String rateType = rate != null ? (rate == true ? "Good" : "Bad") : "" ;


    return NotificationInfo.instance()

            .setFrom("support")
            .to(new LinkedList<String>(receivers))
            .with(NotificationUtils.CREATOR, raterUsername)
            .with(NotificationUtils.ASSIGNEE, ticket.getAssignee())
            .with(NotificationUtils.TICKET_URL, ticketUrl)
            .with(NotificationUtils.TICKET_ID, ticketId)
            .with(NotificationUtils.SPACE_NAME, space != null ? space.getDisplayName().replaceAll("(?i)^(client|customer)","").trim() : "Customer" )
            .with(NotificationUtils.TICKET_TITLE, ticketTitle)
            .with(NotificationUtils.TICKET_STATUS, ticket.getStatus())
            .with(NotificationUtils.RATED_FROM, isRatedFromMail ? "Email" : "Web")
            .with(NotificationUtils.RATE_TYPE,rateType)
            .key(getKey()).end();
  }
}