package ru.micord.ervu.account_applications.service.processor.impl;


import java.sql.Timestamp;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import ru.micord.ervu.account_applications.dao.RoleDao;
import ru.micord.ervu.account_applications.db_beans.public_.tables.records.UserApplicationRoleRecord;
import ru.micord.ervu.account_applications.model.RoleData;
import ru.micord.ervu.account_applications.service.processor.DataProcessor;

/**
 * @author Adel Kalimullin
 */
@Component
public class RoleProcessor implements DataProcessor<RoleData, UserApplicationRoleRecord> {
  private final RoleDao dao;
  @Value("${ervu.admin.role:gomu_supervisor, system_administrator, security_administrator, Responsible_for_internal_control}")
  private String ervuAdminRole;
  private String[] adminRoles;

  public RoleProcessor(RoleDao dao) {
    this.dao = dao;
  }

  @PostConstruct
  private void init() {
    adminRoles = Arrays.stream(ervuAdminRole.split(","))
        .map(String::trim)
        .toArray(String[]::new);
  }

  @Override
  public void upsertData(RoleData roleData) {
    UserApplicationRoleRecord roleRecord = mapToRecord(roleData);
    dao.upsertData(roleRecord);
  }

  @Override
  public void changeActiveStatus(List<String> ids, boolean active) {
    dao.setActiveStatus(ids, active);
  }

  @Override
  public Class<RoleData> getType() {
    return RoleData.class;
  }

  @Override
  public UserApplicationRoleRecord mapToRecord(RoleData data) {
    Timestamp updatedAt = Timestamp.from(Instant.ofEpochMilli(data.getModified()));
    Timestamp createdAt = Timestamp.from(Instant.ofEpochMilli(data.getCreated()));
    Timestamp deletedAt = Timestamp.from(Instant.ofEpochMilli(data.getDeleted()));
    UserApplicationRoleRecord record = dao.newRecord();
    record.setUserRoleId(data.getId());
    record.setRoleName(data.getDisplayName());
    record.setRoleCode(data.getName());
    record.setActive(data.getActive());
    record.setCreated(createdAt);
    record.setDeleted(deletedAt);
    record.setUpdated(updatedAt);
    record.setVersion(data.getVersion());

    boolean isAdminRole = Arrays.stream(adminRoles)
        .anyMatch(role -> role.equalsIgnoreCase(data.getName()));

    record.setAdminRole(isAdminRole ? true : null);

    return record;
  }
}
