/*
 * Copyright (c) 2008-2016 Haulmont.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.company.testoracle.core;

import com.haulmont.bali.db.QueryRunner;
import com.haulmont.cuba.core.Persistence;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.listener.AfterCompleteTransactionListener;
import com.haulmont.cuba.security.entity.User;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.sql.SQLException;
import java.util.Collection;

@Component("oracletest_TestAfterCommitTxListener")
public class TestAfterCompleteTxListener implements AfterCompleteTransactionListener {

    public static String test;
    public static volatile boolean ok = false;

    @Inject
    private Persistence persistence;

    @Override
    public void afterComplete(boolean committed, Collection<Entity> detachedEntities) {
        if (test != null) {
            switch (test) {
                case "test":
                    test(committed, detachedEntities);
                    break;
            }
        }
    }

    private void test(boolean committed, Collection<Entity> detachedEntities) {
        if (!committed)
            return;

        User user = null;
        for (Entity entity : detachedEntities) {
            if (entity instanceof User && ((User) entity).getLogin().startsWith("TxLstnrTst-1-"))
                user = (User) entity;
        }

        if (user != null) {
            try {
                QueryRunner runner = new QueryRunner(persistence.getDataSource());
                String name = runner.query("select name from SEC_USER where login_lc like 'txlstnrtst-1-%'", rs -> {
                    if (rs.next()) {
                        return rs.getString(1);
                    } else {
                        return null;
                    }
                });
                if ("testOracle".equals(name)) {
                    System.out.println("OK");
                    ok = true;
                } else {
                    System.out.println("NOT-OK");
                    ok = false;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
