package org.carlspring.strongbox.crontask.db;

import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;

import java.util.function.Consumer;
import java.util.function.Function;

/**
 *
 * @author Yougeshwar
 */
public class DbUtils
{
    public static <R> R withDatabase(Function<OObjectDatabaseTx, R> code)
    {
        // for simplicity use inmemory database
        // TODO Replace it with remote instance!
        OObjectDatabaseTx db = new OObjectDatabaseTx("memory:crontasks");
        try
        {
            if (db.exists())
            {
                ODatabaseRecordThreadLocal.INSTANCE.set(db.getUnderlying());
                db.open("admin", "admin");
            }
            else
            {
                db.create();
            }
            return code.apply(db);
        }
        finally
        {
/*            if (!db.isClosed())
            {
                db.close();
            }*/
        }
    }

//    public static void withDatabase(Consumer<OObjectDatabaseTx> code)
//    {
//        // for simplicity use inmemory database
//        // TODO Replace it with remote instance!
//        OObjectDatabaseTx db = new OObjectDatabaseTx("memory:crontasks");
//        try
//        {
//            if (db.exists())
//            {
//                ODatabaseRecordThreadLocal.INSTANCE.set(db.getUnderlying());
//                db.open("admin", "admin");
//            }
//            else
//            {
//                db.create();
//            }
//
//            code.accept(db);
//        }
//        finally
//        {
///*            if (!db.isClosed())
//            {
//                db.close();
//            }*/
//        }
//    }

}

@@ -1014,756 +1014,6 @@
   %7D%0A
-%0A//    public static void withDatabase(Consumer%3COObjectDatabaseTx%3E code)%0A//    %7B%0A//        // for simplicity use inmemory database%0A//        // TODO Replace it with remote instance!%0A//        OObjectDatabaseTx db = new OObjectDatabaseTx(%22memory:crontasks%22);%0A//        try%0A//        %7B%0A//            if (db.exists())%0A//            %7B%0A//                ODatabaseRecordThreadLocal.INSTANCE.set(db.getUnderlying());%0A//                db.open(%22admin%22, %22admin%22);%0A//            %7D%0A//            else%0A//            %7B%0A//                db.create();%0A//            %7D%0A//%0A//            code.accept(db);%0A//        %7D%0A//        finally%0A//        %7B%0A///*            if (!db.isClosed())%0A//            %7B%0A//                db.close();%0A//            %7D*/%0A//        %7D%0A//    %7D%0A%0A
 %7D%0A

Implement cron tasks