package org.exoplatform.cs.service.util;

import java.text.SimpleDateFormat;
import java.util.*;


import org.exoplatform.calendar.service.CalendarService;
import org.exoplatform.calendar.service.CalendarSetting;
import org.exoplatform.commons.utils.CommonsUtils;
import org.exoplatform.commons.utils.ListAccess;
import org.exoplatform.commons.utils.PropertyManager;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.cs.listener.ForumListener;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.services.organization.User;
import org.exoplatform.services.security.ConversationState;
import org.exoplatform.services.security.Identity;

/**
 * Created by IntelliJ IDEA.
 * User: ali
 * Date: 30/01/17
 * Time: 17:55
 */
public class CSUtils {
  private static final Log LOG = ExoLogger.getLogger(ForumListener.class);

  private static final String SUPPORT_GROUP_NAME_CONFIGURATION = "exo.addon.cs.support.group.name";
  private static final String MANAGERS_GROUP_NAME_CONFIGURATION = "exo.addon.cs.managers.group.name";

  public static List<User> getSupportMembers() throws Exception {
    return getGroupMembers(getSupportTeamGroup());
  }

  /**
   * Get the group ID for the support team
   * @return
   */
  public static String getSupportTeamGroup() {
    String groupId = PropertyManager.getProperty(SUPPORT_GROUP_NAME_CONFIGURATION);
    if (groupId == null || groupId.isEmpty()){
      groupId = "support-team";
    }
    return groupId;
  }


  public static List<User> getSupportManagers() throws Exception {
    return getGroupMembers(getSupportManagersGroup());
  }

  /**
   * Get the group ID for the support team
   * @return
   */
  public static String getSupportManagersGroup() {
    String groupId = PropertyManager.getProperty(MANAGERS_GROUP_NAME_CONFIGURATION);
    if (groupId == null || groupId.isEmpty()){
      groupId = "gss";
    }
    return groupId;
  }


  public static List<User> getGroupMembers(String groupId) throws Exception {
    PortalContainer container = PortalContainer.getInstance();
    OrganizationService organizationService = container.getComponentInstanceOfType(OrganizationService.class);
    ListAccess<User> engSupportList = organizationService.getUserHandler().findUsersByGroupId(groupId);
    User[] users = engSupportList.load(0, engSupportList.getSize());
    return Arrays.asList(users);
  }

  public static boolean isMemberof(String user, String groupId) {
    PortalContainer container = PortalContainer.getInstance();
    OrganizationService organizationService = container.getComponentInstanceOfType(OrganizationService.class);
    try {
      if(organizationService.getMembershipHandler().findMembershipsByUserAndGroup(user,groupId).size() > 0){
        return true;
      }
    } catch (Exception e) {
      LOG.error("Can not check the membership of {} in group {}", user, groupId, e);
      return false;
    }
    return false;
  }


  public static Boolean canManage() {
    Identity currentId = ConversationState.getCurrent().getIdentity();
    if(currentId.isMemberOf("/"+getSupportTeamGroup())||currentId.isMemberOf("/platform/administrators")) return true;
    return false;
  }

  public static Calendar getNextDate(Calendar c, long delay) {
    Calendar next = Calendar.getInstance();
    next.setTime(c.getTime());
    next.setTimeZone(TimeZone.getTimeZone("GMT+01"));
    next.setTimeInMillis(next.getTimeInMillis()+delay);
   while((next.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) || (next.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)){
     next.add(Calendar.DATE, 1);
   }
   return next;
  }


  public static long  getDiffBetweenTwoDates(Calendar c1, Calendar c2) {
    Calendar from=Calendar.getInstance();
    from.setTime(c1.getTime());
    Calendar to=Calendar.getInstance();
    to.setTime(c2.getTime());

    if((from.get(Calendar.HOUR_OF_DAY) > 18)){
      from.add(Calendar.DATE, 1);
      from.set(Calendar.HOUR_OF_DAY,9);
      from.set(Calendar.MINUTE,0);
    }
    if((from.get(Calendar.HOUR_OF_DAY) < 9)){
      from.set(Calendar.HOUR_OF_DAY,9);
      from.set(Calendar.MINUTE,0);
    }
    if((to.get(Calendar.HOUR_OF_DAY) > 18)){
      to.set(Calendar.HOUR_OF_DAY,18);
      to.set(Calendar.MINUTE,0);
    }
    if((to.get(Calendar.HOUR_OF_DAY) < 9)){
      to.add(Calendar.DATE, -1);
      to.set(Calendar.HOUR_OF_DAY,18);
      to.set(Calendar.MINUTE,0);
    }
    while((from.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) || (from.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)){
      from.add(Calendar.DATE, 1);
      from.set(Calendar.HOUR_OF_DAY,9);
      from.set(Calendar.MINUTE,0);
    }
    long diff = to.getTimeInMillis() - from.getTimeInMillis();
    while(from.before(to)){
      if(((from.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) || (from.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY))){
        diff-=24*60*60*1000;
      }
      from.add(Calendar.DATE, 1);
    }
    return diff;
  }


  public static String formatDate(String date, TimeZone timezone) {
    if (date == null) {
      return null;
    }

    Calendar today = Calendar.getInstance(timezone);
    Calendar cal = Calendar.getInstance(timezone);
    cal.setTime(new Date(Long.parseLong(date)));
    String format = "MMM dd yyyy";
    if (cal.get(Calendar.YEAR) == today.get(Calendar.YEAR)) {
      format = "MMM dd";
    }
    SimpleDateFormat df = new SimpleDateFormat(format);
    df.setTimeZone(timezone);
    return df.format(cal.getTime());
  }

  public static 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;
  }

}
