package commons.cmd;
import java.util.ArrayList;
import java.util.List;
import basics.profiler.MemoryInfo;
import basics.time.LongSleep;
import basics.unexpected.Problem;
import basics.utl.Empty;
import basics.utl.SUtl;
import commons.application.GLOBAL;
import commons.application.Application;
import commons.application.core.Command;
import commons.application.ctx.Context;
public class unset extends Command
{

private static final String ARGS = "ARGS: <keyname>|*  (* removes all keys) | <subctx>!<keyname> delete key from all contexts. ";

public void process () throws Exception
{
   String args = ctx.consume(GLOBAL.CTX_ENVKEY_ARG0, "");
   if (Empty.is(args)) throw new Problem("Missing arg. " + ARGS);
   if (args.equals("*"))
   {
      List<String> list = new ArrayList<String>();
      for (String var : ctx.keySet())
         list.add(var);
      for (String var : list)
         ctx.remove(var);
   }
   else
   {
      for (String var : SUtl.split(args, ","))
      {
         int x = var.indexOf(GLOBAL.CTX_TOKEN_SUBKEY_ATT_SEPARATOR);
         if (x == 0)
         { // !a loescht nur in aktuellem ctx
            String subkey = var.substring(x + 1);
            // Manager.ui().put("Removing '" + subkey + "': " + ctx.get(subkey,
            // "empty"));
            ctx.remove(subkey);
            Application.ui().print(
               "Ctx contains '" + subkey + "'? " + ctx.containsKey(subkey) + " in hiera.: " + ctx.containsKeyInHierarchy(subkey));
         }
         else if (x > 0)
         { // k!a wird aus allen erreichbaren ctx entfernt
            String subctxkey = var.substring(0, x);
            String subkey = var.substring(x + 1);
            // Manager.ui().put("Removing '" + subkey + "' from all contexts.");
            Context subctx = ctx.getChildCtxByName(subctxkey);
            subctx.removeInHierarchy(subkey);
         }
         else
         { // a loescht a nur aus aktuellem ctx
            // Manager.ui().put("Removing '" + var + "' from current context.");
            ctx.remove(var);
         }
      }
   }
   MemoryInfo.gc();
   new LongSleep().sleep(300);
   MemoryInfo.gc();
   new LongSleep().sleep(200);
   engine.contextParamsChanged();
}

public void signContract ()
{}

public String description ()
{
   return implName() + " unsets (removes) a key from the context. " + ARGS;
}
}
