/*
 * This file is part of the Meeds project (https://meeds.io/).
 * Copyright (C) 2020 - 2024 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 io.meeds.deeds.common.service;

import static io.meeds.deeds.common.constant.CommonConstants.DEED_USER_PROFILE_SAVED_EVENT;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.meeds.deeds.common.elasticsearch.model.UserProfile;
import io.meeds.deeds.common.elasticsearch.storage.UserProfileRepository;
import io.meeds.deeds.common.model.UserProfileDTO;
import io.meeds.deeds.common.utils.UserProfileMapper;

@Component
public class UserProfileService {

  @Autowired
  private UserProfileRepository userProfileRepository;

  @Autowired
  private ListenerService       listenerService;

  public UserProfileDTO getUserProfile(String address) {
    UserProfile userProfile = userProfileRepository.findByAddress(address.toLowerCase());
    return UserProfileMapper.toDTO(userProfile);
  }

  public void saveUserProfile(UserProfileDTO userProfileDTO) {
    UserProfile userProfile = userProfileRepository.findByAddress(userProfileDTO.getAddress().toLowerCase());
    if (userProfile == null) {
      userProfile = UserProfileMapper.fromDTO(userProfileDTO);
    } else {
      userProfile = UserProfileMapper.fromDTO(userProfileDTO).withId(userProfile.getId());
    }
    userProfile = userProfileRepository.save(userProfile);
    listenerService.publishEvent(DEED_USER_PROFILE_SAVED_EVENT, UserProfileMapper.toDTO(userProfile));
  }

}
