/*******************************************************************************
 * Copyright (c), 2001, 2002 N2 Broadband, Inc.  All Rights Reserved.
 *
 * This module contains unpublished, confidential, proprietary
 * material.  The use and dissemination of this material are
 * governed by a license.  The above copyright notice does not
 * evidence any actual or intended publication of this material.
 *
 * Author:  Drake H. Henderson
 * Created:  11-12-01
 *
 ******************************************************************************/

package com.n2bb.sysmonui.alerts;

/**** COMMON IMPORTS BEGIN ****/
import com.n2bb.action.N2bbAction;
import com.n2bb.util.ActionConstants;
import com.n2bb.util.N2bbException;
import com.tandbergtv.workflow.web.common.StaticCodes;

import org.apache.struts.action.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**** COMMON IMPORTS END ******/

public final class AlertAction extends N2bbAction {

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
          HttpServletResponse response) throws IOException, ServletException {

    // defaultAction
    String defaultAction = ActionConstants.add;

    /******************** COMMON BEGIN *********************/
    HttpSession session = request.getSession();

    String action = request.getParameter("actionType");
    if (action == null || action.equals(""))
      action = defaultAction;
    n2bbLog.debug("action... " + action);

    ActionErrors errors = new ActionErrors();
    ActionForward fwd = mapping.findForward("home");
    /******************** COMMON END ***********************/

    try {
      // add alert
      if (action.equals(ActionConstants.add)) {
        if (addAlert(errors, session))
          fwd = mapping.findForward("success");
        else
          fwd = mapping.findForward("failure");
      // save alert
      } else if (action.equals(ActionConstants.save)) {
        if (saveAlert(errors, form))
          fwd = mapping.findForward("success");
        else
          fwd = mapping.findForward("failure");
      // edit alert
      } else if (action.equals(ActionConstants.edit)) {
        if (editAlert(errors, session, request))
          fwd = mapping.findForward("success");
        else
          fwd = mapping.findForward("failure");
      // update alert
      } else if (action.equals(ActionConstants.update)) {
        if (updateAlert(errors, form))
          fwd = mapping.findForward("success");
        else
          fwd = mapping.findForward("failure");
      }
    }
    catch (Exception e) {
      //errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.other"));
      n2bbLog.error(e.getMessage(), e);
    }

    //if (!errors.empty()) {
      //saveErrors(request, errors);
    //}

    return fwd;
  }

  /***************************************
   *
   ***************************************/
  private boolean addAlert(ActionErrors errors, HttpSession session) {
    n2bbLog.debug("enter");

  	try {
      session.setAttribute("alertNameMap", AlertManager.getAlertPatternMap());
      return true;
  	} catch (Exception e) {
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.alertAction.add"));
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.other"));
      n2bbLog.error(e.getMessage(), e);
      return false;
  	}
  }
  
  /************************
   *
   ************************/
  private boolean saveAlert(ActionErrors errors, ActionForm form) {
      try {
        AlertDataBean bean = convertFormToBean((AlertForm)form);
        AlertManager.saveAlert(bean);
        return true;
      } catch (N2bbException e) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.alertAction.save"));
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(e.getErrorCode()));
        n2bbLog.error("failed to save - message... " + e.getMessage(), e);
        return false;
      }
  }

  /************************
   *
   ************************/
  private boolean editAlert(ActionErrors errors, HttpSession session, HttpServletRequest request) {
      try {
        // hack to enable modify menu item
    	request.setAttribute(StaticCodes.MODIFY_ALERT_TAB_ITEM, StaticCodes.MODIFY_ALERT_TAB_ITEM);
    	
        session.setAttribute("alertNameMap", AlertManager.getAlertPatternMap());
      } catch (N2bbException e) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.alertAction.edit"));
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.alertAction.names"));
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(e.getErrorCode()));
        return false;
      }

      // get alert
      try {
        String alertIdentifier = request.getParameter("alertIdentifier");
        AlertDataBean bean = AlertManager.getAlert(alertIdentifier);
        AlertForm form = convertBeanToForm(bean);
        form.setAction(ActionConstants.edit);
        request.setAttribute("alertForm", form);
        
      } catch (N2bbException e) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.alertAction.edit"));
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(e.getErrorCode()));
        n2bbLog.error("failed to get alert exception - message... " + e.getMessage(), e);
        return false;
      }
      return true;
  }

  /************************
   *
   ************************/
  private boolean updateAlert(ActionErrors errors, ActionForm form) {
      try {
        AlertDataBean bean = convertFormToBean((AlertForm)form);
        AlertManager.updateAlert(bean);
      } catch (N2bbException e) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.alertAction.update"));
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(e.getErrorCode()));
        n2bbLog.error("failed to update - message... " + e.getMessage(), e);
        return false;
      }

      return true;
  }

  /************************
   *
   ************************/
  private AlertDataBean convertFormToBean(AlertForm form) {
    AlertDataBean bean = new AlertDataBean();
    bean.setAlertIdentifier(form.getAlertIdentifier());
    bean.setAlertPattern(form.getAlertPattern());
    
    int fc;
    try {
      fc = Integer.parseInt(form.getFrequencyCount());
    } catch (Exception e) {
      fc = 1;
    }
    bean.setFrequencyCount(fc);

    // freq time
    int fhr = 0;
    int fmin = 0;
    int fsec = 0;
    int ftot = 0;
    try {
      fhr = Integer.parseInt(form.getFrequencyHr()) * 3600;
    } catch (Exception e) {}
    try {
      fmin = Integer.parseInt(form.getFrequencyMin()) * 60;
    } catch (Exception e) {}
    try {
      fsec = Integer.parseInt(form.getFrequencySec());
    } catch (Exception e) {}
    ftot = fhr + fmin + fsec;
    bean.setFrequencySecs(ftot);

    int tc;
    try {
      tc = Integer.parseInt(form.getThresholdCount());
    } catch (Exception e) {
      tc = 1;
    }
    bean.setThresholdCount(tc);
    
    // thresh time
    int thr = 0;
    int tmin = 0;
    int tsec = 0;
    int ttot = 0;
    try {
      thr = Integer.parseInt(form.getThresholdHr()) * 3600;
    } catch (Exception e) {}
    try {
      tmin = Integer.parseInt(form.getThresholdMin()) * 60;
    } catch (Exception e) {}
    try {
      tsec = Integer.parseInt(form.getThresholdSec());
    } catch (Exception e) {}
    ttot = thr + tmin + tsec;
    bean.setThresholdSecs(ttot);
    
    if (form.getChkEmail())
      bean.setEmail(form.getTxtEmail());
      
    if (form.getChkSnmp())
      bean.setSNMP(form.getTxtSnmp());

    return bean;
  }

  /************************
   *
   ************************/
  private AlertForm convertBeanToForm(AlertDataBean bean) {
    AlertForm form = new AlertForm();
    form.setAlertIdentifier(bean.getAlertIdentifier());
    form.setAlertPattern(bean.getAlertPattern());
    
    form.setFrequencyCount(bean.getFrequencyCount()+"");

    int fseconds = 0;
    int fminutes = 0;
    int fhours = 0;
    fhours = bean.getFrequencySecs() / 3600;
    int fsecsLeft = bean.getFrequencySecs() % 3600;
    if (fsecsLeft != 0) {
      if (fsecsLeft > 59) {
        fminutes = fsecsLeft / 60;
        fseconds = fsecsLeft % 60;
      } else
        fseconds = fsecsLeft;
    }

    form.setFrequencyHr(fhours+"");
    form.setFrequencyMin(fminutes+"");
    form.setFrequencySec(fseconds+"");

    form.setThresholdCount(bean.getThresholdCount()+"");

    int tseconds = 0;
    int tminutes = 0;
    int thours = 0;
    thours = bean.getThresholdSecs() / 3600;
    int tsecsLeft = bean.getThresholdSecs() % 3600;
    if (tsecsLeft != 0) {
      if (tsecsLeft > 59) {
        tminutes = tsecsLeft / 60;
        tseconds = tsecsLeft % 60;
      } else
        tseconds = tsecsLeft;
    }

    form.setThresholdHr(thours+"");
    form.setThresholdMin(tminutes+"");
    form.setThresholdSec(tseconds+"");
    
    if (!bean.getEmail().equals("")) {
      form.setChkEmail(true);
      form.setTxtEmail(bean.getEmail());
    }
      
    if (!bean.getSNMP().equals("")) {
      form.setChkSnmp(true);
      form.setTxtSnmp(bean.getSNMP());
    }
    
    return form;
  }

}

