/**
 * This file is part of the Meeds project (https://meeds.io/).
 *
 * Copyright (C) 2020 - 2025 Meeds Association contact@meeds.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package org.exoplatform.social.core.identity.provider;

import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.social.core.activity.model.ActivityStream;
import org.exoplatform.social.core.identity.IdentityProvider;
import org.exoplatform.social.core.identity.model.Identity;
import org.exoplatform.social.core.identity.model.Profile;
import org.exoplatform.social.core.space.model.Space;
import org.exoplatform.social.core.space.spi.SpaceService;

/**
 * Provides the identity for a space
 */
public class SpaceIdentityProvider extends IdentityProvider<Space> {

  private static final Log LOG = ExoLogger.getExoLogger(SpaceIdentityProvider.class);

  public static final String NAME = ActivityStream.SPACE_PROVIDER_ID;

  private SpaceService spaceService;

  /**
   * Constructor
   *
   * @param spaceService
   */
  public SpaceIdentityProvider(SpaceService spaceService) {
    this.spaceService = spaceService;
  }

  /**
   * Finds a space by its remote Id (pretty name or space id).
   *
   * @param spacePrettyName could be spacePrettyName or spaceId
   * @return
   */
  public Space findByRemoteId(String spacePrettyName) {
    Space space = null;
    try {
      space = spaceService.getSpaceByPrettyName(spacePrettyName);
      // attempt to find by pretty name
      if (space == null) {
        space = spaceService.getSpaceById(spacePrettyName);
      }
    } catch (Exception e) {
      LOG.error("Could not find space " + spacePrettyName, e);
    }
    return space;
  }

  @Override
  public String getName() {
    return NAME;
  }

  @Override
  public Identity createIdentity(Space space) {
    Identity identity = new Identity(NAME, space.getPrettyName());
    return identity;
  }

  @Override
  public void populateProfile(Profile profile, Space space) {
    profile.setAvatarUrl(space.getAvatarUrl());
    profile.setUrl(space.getUrl());
    profile.setProperty(Profile.FULL_NAME, space.getDisplayName());
  }
}
