package ervu_business_metrics.service.processor.impl;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import ervu_business_metrics.config.KafkaEnabledCondition;
import ervu_business_metrics.model.idm.RoleData;
import ervu_business_metrics.service.IdmDirectoriesDaoService;
import ervu_business_metrics.service.processor.DataProcessor;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import ru.micord.webbpm.ervu.business_metrics.db_beans.idm_reconcile.tables.records.RoleRecord;

/**
 * @author Adel Kalimullin
 */
@Component
@Conditional(KafkaEnabledCondition.class)
public class RoleDataProcessor implements DataProcessor<RoleData> {
  private final IdmDirectoriesDaoService idmDirectoriesDaoService;

  public RoleDataProcessor(IdmDirectoriesDaoService idmDirectoriesDaoService) {
    this.idmDirectoriesDaoService = idmDirectoriesDaoService;
  }

  @Override
  public void upsertData(List<RoleData> dataList) {
    List<RoleRecord> newRoleRecords = new ArrayList<>();
    List<RoleRecord> roleRecords = new ArrayList<>();
    Set<String> existingIds = idmDirectoriesDaoService.getRoleIds();

    for (RoleData data : dataList) {
      if (!data.isErvuRole()) {
        continue;
      }
      RoleRecord record = idmDirectoriesDaoService.getRoleRecord();
      Timestamp modifiedAt = Timestamp.from(Instant.ofEpochMilli(data.getModified()));

      record.setId(data.getId());
      record.setName(data.getName());
      record.setDisplayName(data.getDisplayName());
      record.setShortname(data.getShortname());
      record.setSchema(data.getSchema());
      record.setVersion(data.getVersion());
      record.setSessionsLimit(data.getSessionsLimit());
      record.setImported(data.getImported());
      record.setDescription(data.getDescription());
      record.setErvuRole(data.isErvuRole());
      record.setModified(modifiedAt);

      if (existingIds.contains(data.getId())) {
        roleRecords.add(record);
      }
      else {
        newRoleRecords.add(record);
      }
    }

    if (!newRoleRecords.isEmpty()) {
      idmDirectoriesDaoService.insertRoleRecords(newRoleRecords);
    }

    if (!roleRecords.isEmpty()) {
      idmDirectoriesDaoService.updateRoleRecords(roleRecords);
    }
  }

  @Override
  public void deleteData(List<String> ids) {
    // TODO удаление пока не реализовано
  }
}
