package cz.moneta.test.dsl.util.task.nasdb;

import cz.moneta.test.dsl.util.data.client.NonClient;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.nasdb.NasDbEndpoint;
import org.jooq.Record;
import org.jooq.Result;

import java.util.ArrayList;
import java.util.List;

public class NasDbTasks {

    private final StoreAccessor harness;

    public NasDbTasks(StoreAccessor harness) {
        this.harness = harness;
    }

    public void insertUser(NonClient client) {
        harness.getEndpoint(NasDbEndpoint.class)
                .insertUser(client.birthNumber(), client.firstName(), client.lastName());
    }

    /**
     * Method try to find ID Card from input on blacklist in NAS DB
     *
     * @param id id card number
     * @return true when present
     */
    public boolean checkPresentIdOnBlacklist(String id) {
        return harness.getEndpoint(NasDbEndpoint.class).checkPresentIdCardOnBlacklist(id);
    }

    /**
     * Returns a list of application ids of all applications not in declined or canceled state
     *
     * @param birthNumber client birth number
     */

    public List<String> getAllPendingApllicationsForClient(String birthNumber) {
        String sql = "select a.appl_id from nasdb_owner.appl a "
                + " join nasdb_owner.appl_stat ast on ast.appl_stat_key = a.appl_stat_key"
                + " join nasdb_owner.appl_pt_role ar on ar.appl_key=a.appl_key"
                + " join nasdb_owner.inst_pt i on i.inst_pt_key = ar.inst_pt_key"
                + String.format(" where i.rc_num = '%s'", birthNumber)
                + " and ast.descr not in ('Storno', 'Zamítnutá', 'Chyba', 'Podepsaná')";
        ArrayList<String> applList = new ArrayList<>();
        Result<Record> resultList = harness.getEndpoint(NasDbEndpoint.class).executeSql(sql);
        resultList.forEach(result -> applList.add(result.getValue("APPL_ID").toString()));

        return applList;
    }
}
