package ru.micord.ervu.account_applications.dao;

import java.sql.Timestamp;
import java.time.LocalDateTime;

import org.jooq.DSLContext;
import org.springframework.stereotype.Repository;

import static ru.micord.ervu.account_applications.db_beans.public_.tables.UserApplicationList.USER_APPLICATION_LIST;
import static ru.micord.ervu.account_applications.enums.ApplicationStatus.ACCEPTED;
import static ru.micord.ervu.account_applications.enums.ApplicationStatus.AGREED;
import static ru.micord.ervu.account_applications.enums.ApplicationStatus.SENT;

/**
 * @author gulnaz
 */
@Repository
public class UserApplicationListDao {

  private DSLContext dslContext;

  public UserApplicationListDao(DSLContext dslContext) {
    this.dslContext = dslContext;
  }

  public void savePassword(Long appNumber, String encodedPass) {
    dslContext.update(USER_APPLICATION_LIST)
        .set(USER_APPLICATION_LIST.APPLICATION_STATUS, ACCEPTED.name())
        .set(USER_APPLICATION_LIST.USER_PASSWORD, encodedPass)
        .where(USER_APPLICATION_LIST.NUMBER_APP.eq(appNumber))
        .execute();
  }

  public void saveAcceptedStatus(long appNumber) {
    dslContext.update(USER_APPLICATION_LIST)
        .set(USER_APPLICATION_LIST.APPLICATION_STATUS, ACCEPTED.name())
        .where(USER_APPLICATION_LIST.NUMBER_APP.eq(appNumber))
        .execute();
  }

  public void saveError(long appNumber, String errorMsg) {
    dslContext.update(USER_APPLICATION_LIST)
        .set(USER_APPLICATION_LIST.APPLICATION_STATUS, AGREED.name())
        .set(USER_APPLICATION_LIST.EDIT_COMMENT, errorMsg)
        .where(USER_APPLICATION_LIST.NUMBER_APP.eq(appNumber))
        .execute();
  }

  public boolean userExists(String login) {
    return dslContext.fetchExists(
        dslContext.selectOne()
            .from(USER_APPLICATION_LIST)
            .where(USER_APPLICATION_LIST.USER_LOGIN.eq(login)));
  }

  public void saveAgreedStatusForSentAppsOlderThan(long minutes) {
    dslContext.update(USER_APPLICATION_LIST)
        .set(USER_APPLICATION_LIST.APPLICATION_STATUS, AGREED.name())
        .where(USER_APPLICATION_LIST.APPLICATION_STATUS.eq(SENT.name())
            .and(USER_APPLICATION_LIST.SENT_DATE.lessOrEqual(
                Timestamp.valueOf(LocalDateTime.now().minusMinutes(minutes)))))
        .execute();
  }
}
