package ru.micord.ervu.service;

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

import ervu_lkrp_ul.ervu_lkrp_ul.db_beans.public_.tables.records.InteractionLogRecord;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static ervu_lkrp_ul.ervu_lkrp_ul.db_beans.public_.tables.InteractionLog.INTERACTION_LOG;

/**
 * @author Eduard Tihomirov
 */
@Service
public class InteractionServiceImpl implements InteractionService {

  @Autowired
  private DSLContext dslContext;

  @Override
  public List<InteractionLogRecord> get(String ervuId, String[] excludedStatuses) {
    Condition condition = INTERACTION_LOG.ERVU_ID.eq(ervuId);

    if (excludedStatuses != null && excludedStatuses.length > 0) {
      condition = condition.and(INTERACTION_LOG.STATUS.notIn(excludedStatuses));
    }
    return dslContext.selectFrom(INTERACTION_LOG)
        .where(condition)
        .fetch();
  }

  public void setStatus(String fileId, String status, String fileName, String form,
      Timestamp timestamp, String sender, String ervuId) {
    dslContext.insertInto(INTERACTION_LOG)
        .set(INTERACTION_LOG.FILE_ID, fileId)
        .set(INTERACTION_LOG.STATUS, status)
        .set(INTERACTION_LOG.FORM, form)
        .set(INTERACTION_LOG.SENT_DATE, timestamp)
        .set(INTERACTION_LOG.SENDER, sender)
        .set(INTERACTION_LOG.FILE_NAME, fileName)
        .set(INTERACTION_LOG.RECORDS_SENT, 0)
        .set(INTERACTION_LOG.RECORDS_ACCEPTED, 0)
        .set(INTERACTION_LOG.ERVU_ID, ervuId)
        .execute();
  }

  public void updateStatus(String fileId, String status, String ervuId) {
    dslContext.update(INTERACTION_LOG)
        .set(INTERACTION_LOG.STATUS, status)
        .where(INTERACTION_LOG.ERVU_ID.eq(ervuId))
        .and(INTERACTION_LOG.FILE_ID.eq(fileId))
        .execute();
  }

  public void delete(String fileId, String ervuId) {
    dslContext.deleteFrom(INTERACTION_LOG)
        .where(INTERACTION_LOG.ERVU_ID.eq(ervuId)
            .and(INTERACTION_LOG.FILE_ID.eq(fileId)))
        .execute();
  }
}
