package commons.utl;
import java.io.File;
import basics.dictionaries.Termset;
import basics.dictionaries.Transducer;
import basics.profiler.Profiler;
import basics.unexpected.Problem;
import basics.utl.Empty;
import commons.application.GLOBAL;
import commons.application.ctx.Context;
/**
 * Expects an transducer file in the work folder. Filename format: <key>.txt, where <key> would be
 * something like "transducer_de", "transducer_en", etc.
 * @author kst
 */
public class TransducerCtxUtl
{

/**
 * @param ctx
 * @param key - key for accessing the transducer and the file
 */
public static void load (Context ctx, String key)
{
   Profiler.resume(GLOBAL.IO_TOKEN);
   String home = CtxUtl.userShared(ctx);
   String ext = Empty.is(GLOBAL.TRANSDUCER_EXTENSION) ? "" : "." + GLOBAL.TRANSDUCER_EXTENSION;
   Transducer t = new Transducer(new File(home, key + ext));
   if (t != null)
      ctx.put(key + GLOBAL.TRANSDUCER_EXTENSION, t);
   Profiler.stop(GLOBAL.IO_TOKEN);
   Profiler.increment(GLOBAL.IO_TOKEN, 1);
}

//not used
public static void save (Context ctx, String key) throws Problem
{
   Profiler.resume(GLOBAL.IO_TOKEN);
   String home = CtxUtl.userShared(ctx);
   String ext = Empty.is(GLOBAL.TRANSDUCER_EXTENSION) ? "" : "." + GLOBAL.TRANSDUCER_EXTENSION;
   Transducer t = (Transducer) ctx.getr(key, (Termset) null);
   if (t != null)
      t.saveToFile(new File(home, key + ext));
   Profiler.stop(GLOBAL.IO_TOKEN);
   Profiler.increment(GLOBAL.IO_TOKEN, 1);
}

public static Transducer get (Context ctx, String tkey)
{
   return (Transducer) ctx.getr(tkey, (Transducer) null);
}

public static String transduceOrReturnNull (String tkey, Context ctx, String term)
{
   Transducer t = (Transducer) ctx.getr(tkey, (Transducer) null);
   return (t == null) ? term : t.transduceOrNull(term);
}

public static String transduceOrReturnInput (String tkey, Context ctx, String term)
{
   Transducer t = (Transducer) ctx.getr(tkey, (Transducer) null);
   return (t == null) ? null : t.transduceOrReturn(term);
}
}
