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

static String[] tkeyArray = null;

public static boolean noStopwordsDefined (Context ctx)
{
   if (tkeyArray == null)
      tkeyArray = SUtl.split(ctx.getr(GLOBAL.CTX_KEY_STOPLISTS, ""), ",");
   for (String tkey : tkeyArray)
      if (get(ctx, tkey + GLOBAL.STOPWORDS_EXTENSION).size() > 0)
         return false;
   return true;
}

/**
 * @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.STOPWORDS_EXTENSION) ? "" : "." + GLOBAL.STOPWORDS_EXTENSION;
   Termset t = Termset.loadFromFile(new File(home, key + ext).getAbsolutePath());
   if (t != null)
      ctx.put(key + GLOBAL.STOPWORDS_EXTENSION, t);
   Profiler.stop(GLOBAL.IO_TOKEN);
   Profiler.increment(GLOBAL.IO_TOKEN, 1);
}

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

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

public static boolean contains (String tkey, Context ctx, String term)
{
   Termset t = (Termset) ctx.getr(tkey, (Termset) null);
   return (t == null) ? false : t.contains(term);
}

/**
 * check all known stoplists
 * @param ctx
 * @param term
 * @return
 */
public static boolean contains (Context ctx, String term)
{
   if (tkeyArray == null)
      tkeyArray = SUtl.split(ctx.getr(GLOBAL.CTX_KEY_TRANSDUCERS, ""), ",");
   for (String tkey : tkeyArray)
      if (contains(tkey + GLOBAL.STOPWORDS_EXTENSION, ctx, term))
         return true;
   return false;
}
}
