package net.javacrumbs.shedlock.provider.jdbctemplate;

import net.javacrumbs.shedlock.core.LockConfiguration;
import net.javacrumbs.shedlock.support.annotation.NonNull;

import java.util.HashMap;
import java.util.Map;

class Db2ServerTimeStatementsSource extends SqlStatementsSource {
    private final String now = "(CURRENT TIMESTAMP - CURRENT TIMEZONE)";
    private final String lockAtMostFor = "("+ now + " + :lockAtMostForSeconds SECONDS)";

    Db2ServerTimeStatementsSource(JdbcTemplateLockProvider.Configuration configuration) {
        super(configuration);
    }

    @Override
    String getInsertStatement() {
        return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)";
    }

    @Override
    public String getUpdateStatement() {
        return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now;
    }

    @Override
    public String getUnlockStatement() {
        String lockAtLeastFor = "ADD_SECONDS(" + lockedAt() + ", :lockAtLeastForSeconds)";
        return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy";
    }

    @Override
    public String getExtendStatement() {
        return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now;
    }

    @Override
    @NonNull
    Map<String, Object> params(@NonNull LockConfiguration lockConfiguration) {
        Map<String, Object> params = new HashMap<>();
        params.put("name", lockConfiguration.getName());
        params.put("lockedBy", configuration.getLockedByValue());
        params.put("lockAtMostForSeconds", ((double) lockConfiguration.getLockAtMostFor().toMillis()) / 1000);
        params.put("lockAtLeastForSeconds", ((double) lockConfiguration.getLockAtLeastFor().toMillis()) / 1000);
        return params;
    }
}

@@ -1188,19 +1188,8 @@
  = %22
-ADD_SECONDS
 (%22 +
@@ -1199,25 +1199,25 @@
 ckedAt() + %22
-,
++
  :lockAtLeas
@@ -1227,16 +1227,24 @@
 rSeconds
+ SECONDS
 )%22;%0A    

Fix for SQLCODE=-440 on DB2