package ru.micord.ervu.account_applications.service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.micord.ervu.account_applications.component.dao.AuditDao;
import ru.micord.ervu.account_applications.dao.UserApplicationListDao;
import utils.DateTimeUtil;

import static ru.micord.ervu.account_applications.enums.ApplicationStatus.ACCEPTED;
import static ru.micord.ervu.account_applications.enums.ApplicationStatus.AGREED;

/**
 * @author gulnaz
 */
@Service
public class UserApplicationListService {

  private final UserApplicationListDao dao;
  private final AuditDao auditDao;

  public UserApplicationListService(UserApplicationListDao dao, AuditDao auditDao) {
    this.dao = dao;
    this.auditDao = auditDao;
  }

  public Map<Long, String> getStatusesBatch(List<Long> appNumbers) {
    return dao.getStatusesBatch(appNumbers);
  }

  @Transactional
  public void savePassword(Long appNumber, String encodedPass, String name, String userId) {
    dao.savePassword(appNumber, encodedPass);
    saveAuditStatusByAppNumber(appNumber, ACCEPTED.name(), name, userId);
  }

  public boolean userExists(String login){
    return dao.userExists(login);
  }

  @Transactional
  public void saveAcceptedStatus(long appNumber, String name, String userId) {
    dao.saveAcceptedStatus(appNumber);
    saveAuditStatusByAppNumber(appNumber, ACCEPTED.name(), name, userId);
  }

  @Transactional
  public void saveError(long appNumber, String errorMsg, String name, String userId) {
    dao.saveError(appNumber, errorMsg);
    saveAuditStatusByAppNumber(appNumber, AGREED.name(), name, userId);
  }

  private void saveAuditStatusByAppNumber(long appNumber, String status, String name, String userId) {
    List<Long> appIds = auditDao.selectAppListIdsByAppNumber(appNumber);
    appIds.forEach(id -> {
      auditDao.insert(id, name, userId, status, Timestamp.valueOf(
          DateTimeUtil.dateToLocalDateTimeUtc(new Date())));
    });
  }
}
