
package de.ivu.elect.presentation.konfiguration.action;

import java.io.File;

import javax.annotation.Nonnull;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;

import de.ivu.elect.business.konfiguration.entity.Konfiguration;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.jee.faces.FacesContextUtil;
import de.ivu.elect.jee.faces.FacesMessageUtil;

@Named(KonfigurationCreateVerzeichnisAction.COMPONENT_NAME)
public class KonfigurationCreateVerzeichnisAction extends AbstractKonfigurationAction {

  public static final String COMPONENT_NAME = "konfigurationCreateVerzeichnisAction";

  private static final long serialVersionUID = 1L;

  public KonfigurationCreateVerzeichnisAction() {
    super();
  }

  @Override
  protected UseCasePermission getRequiredPermission() {
    return UseCasePermission.KONFIGURATION_CREATE_VERZEICHNIS;
  }

  @Override
  protected boolean isDisabledInternal(@Nonnull Konfiguration konfiguration) {
    return !konfiguration.getWertTyp().expectsWertIsVerzeichnis() || StringUtils.isBlank(konfiguration.getWert()) || konfiguration.isValid();
  }

  @Override
  protected boolean isDisabledInternalOnRowDblselect(@Nonnull Konfiguration konfiguration) {
    return true;
  }

  @Override
  protected String doIt(Konfiguration konfiguration) {
    try {
      File verzeichnis = new File(konfiguration.getWert());
      if (verzeichnis.mkdirs()) {
        FacesMessageUtil.addInfoMessage("konfiguration.action.create.verzeichnis.success", "konfiguration.action.create.verzeichnis.success",
            konfiguration.getWert());
      } else {
        FacesMessageUtil.addErrorMessage("konfiguration.action.create.verzeichnis.error");
      }
    } catch (Exception e) {
      FacesMessageUtil.addErrorMessage("konfiguration.action.create.verzeichnis.error.exception", "konfiguration.action.create.verzeichnis.error.exception", e.getMessage());
    }

    return FacesContextUtil.getCurrentViewId();
  }

  @Override
  protected boolean isFireChangeEvent() {
    return true;
  }

  @Override
  public String getLabelKey() {
    return "konfiguration.action.create.verzeichnis";
  }

  @Override
  public String getIcon() {
    return appIcons.getIconFolderOpen();
  }
}
