package nxm.sys.intr;

import nxm.sys.lib.BaseFile;
import nxm.sys.lib.DataFile;
import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.Midas;

/**
  Erase a list of Midas or non-Midas file.

  @author Jeff Schoen / Jay Hallam
*/
public class Erase extends Intrinsic {

  boolean all,warn,quiet;

  /** default constructor */
  public Erase () {}

  public int process() {

    all = MA.getState("/ALL");
    warn = MA.getState("/WARN",true);
    quiet = MA.getState("/QUIET",!verbose);

    for (int i=1; i<=MA.numberOf(); i++) {
      BaseFile bf = MA.getFile(i);

      /* Try a standard erase where BLUE files' DETACHED headers and such are cleaned up... */
      try {
        eraseFile (M,bf,!quiet,warn,all);
      } catch (Exception e) {
        /* ...and if that does not work, treat it as a standard file */
        bf = MA.getBaseFile(i);
        eraseFile (M,bf,!quiet,warn,all);
      }
    }
    return FINISH;
  }

  /** Erase the file
   *  @param M       Midas context
   *  @param bf      File to be erased
   *  @param verbose verbose output flag
   *  @param warn    warning flag
   *  @param force   force flag
   */
  public static void eraseFile (Midas M, BaseFile bf, boolean verbose, boolean warn, boolean force) {
    int status = bf.erase(force);
    if (status==0) {
      if (warn) M.warning ("ERASE: Could not find URL=" + bf.getFileName().getFullName());
    }
    else if (status == DataFile.E_PROT_FAIL) {
      M.warning ("Cannot erase protected URL=" + bf.getFileName().getFullName());
    }
    else if (bf instanceof DataFile) {
      DataFile df = (DataFile)bf;
      if ((status&DataFile.E_HCB_FAIL)!=0 && warn) M.warning ("Trouble deleting URL="+df.ioh.getURL());
      if ((status&DataFile.E_DET_FAIL)!=0 && warn) M.warning ("Trouble deleting detach data URL="+df.io.getURL());
      if ((status&DataFile.E_PKT_FAIL)!=0 && warn) M.warning ("Trouble deleting detach pipe header URL="+df.hp.io.getURL());
      if ((status&DataFile.E_HCB_OK)!=0 && verbose) M.info ("Erased URL="+df.ioh.getURL());
      if ((status&DataFile.E_DET_OK)!=0 && verbose) M.info ("Erased URL="+df.io.getURL());
      if ((status&DataFile.E_PKT_OK)!=0 && verbose) M.info ("Erased URL="+df.hp.io.getURL());
    }
    else if (status<0) {
      if (warn) M.warning ("Trouble deleting URL=" + bf.getFileName().getFullName());
    }
    else if (verbose) {
      M.info ("Erased URL="+bf.io.getURL());
      if (status>1) M.info ("Erased URL=" + ((DataFile)bf).ioh.getURL());
    }
  }

}
