/**
   * Encargado de borrar la informacion de un riego apartir de su identificacion
   *
   * @param idIrr: Identificacion del riego
   * @return Estado del proceso
   */
  public String delete() {
    if (!usrDao.getPrivilegeUser(idUsrSystem, "crop/delete")) {
      return BaseAction.NOT_AUTHORIZED;
    }
    Integer idIrr = 0;
    try {
      idIrr = Integer.parseInt(this.getRequest().getParameter("idIrr"));
    } catch (NumberFormatException e) {
      idIrr = -1;
    }

    if (idIrr == -1) {
      state = "failure";
      info = "Fallo al momento de obtener la informacion a borrar";
      return "states";
    }

    SessionFactory sessions = HibernateUtil.getSessionFactory();
    Session session = sessions.openSession();
    Transaction tx = null;

    try {
      tx = session.beginTransaction();
      Irrigation pr = irrDao.objectById(idIrr);
      pr.setStatus(false);
      //            session.delete(pro);
      session.saveOrUpdate(pr);

      LogEntities log = new LogEntities();
      log.setIdLogEnt(null);
      log.setIdEntityLogEnt(idEntSystem);
      log.setIdObjectLogEnt(pr.getIdIrr());
      log.setTableLogEnt("irrigation");
      log.setDateLogEnt(new Date());
      log.setActionTypeLogEnt("D");
      session.saveOrUpdate(log);
      //            logDao.save(log);
      tx.commit();
      state = "success";
      info = "El riego ha sido borrado con exito";
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
      }
      e.printStackTrace();
      state = "failure";
      info = "Fallo al momento de borrar un riego";
    } finally {
      session.close();
    }

    return "states";
    //        return SUCCESS;
  }
  /**
   * Encargado de guardar la informacion suministrada por el usuario para una siembra
   *
   * @return Estado del proceso
   */
  public String saveData() {
    if (!usrDao.getPrivilegeUser(idUsrSystem, "crop/create")
        || !usrDao.getPrivilegeUser(idUsrSystem, "crop/modify")) {
      return BaseAction.NOT_AUTHORIZED;
    }
    String action = "";
    //        System.out.println("Entre a guardar la info");
    /*
     * Se evalua dependiendo a la accion realizada:
     * 1) create: Al momento de guardar un registro por primera ves
     * 2) modify: Al momento de modificar un registro
     * 3) delete: Al momento de borrar un registro
     */
    if (actExe.equals("create")) {
      action = "C";
    } else if (actExe.equals("modify")) {
      action = "M";
    }

    SessionFactory sessions = HibernateUtil.getSessionFactory();
    Session session = sessions.openSession();
    Transaction tx = null;
    //        info = "La siembra ha sido modificado con exito";

    try {
      tx = session.beginTransaction();

      String dmy = new SimpleDateFormat("yyyy-MM-dd").format(sowing.getDateSow());
      Date dateSow = new SimpleDateFormat("yyyy-MM-dd").parse(dmy);

      //            event.setFields(event.getFields());
      //            event.setCropsTypes(new CropsTypes(2));
      //            event.setIdProjectProEve(event.getIdProjectProEve());
      //            event.setStatus(event.isStatus());
      session.saveOrUpdate(event);

      if (sowing.getIdSow() == null) {
        Sowing sowTemp = sowDao.objectById(idCrop);
        if (sowTemp != null) {
          sowing.setIdSow(sowTemp.getIdSow());
        }
      }

      sowing.setProductionEvents(new ProductionEvents(idCrop));
      sowing.setDateSow(dateSow);
      if (sowing.getChemicalsSowing().getIdCheSow() == -1) {
        sowing.setChemicalsSowing(null);
      }

      if (sowing.getDoseUnits() != null
          && (sowing.getDoseUnits().getIdDosUni() == -1
              || sowing.getChemicalsSowing().getIdCheSow() == 3)) {
        sowing.setDoseUnits(null);
      }
      //            sowing.setSowingTypes(new SowingTypes(idCrop));
      sowing.setStatus(true);
      session.saveOrUpdate(sowing);

      Maize maizeOld = maizeDao.objectById(this.getIdCrop());
      if (maizeOld != null) session.delete(maizeOld);

      Beans beansOld = beansDao.objectById(this.getIdCrop());
      if (beansOld != null) session.delete(beansOld);

      if (typeCrop == 1) {
        maize.setProductionEvents(new ProductionEvents(idCrop));
        maize.setStatus(true);
        session.saveOrUpdate(maize);
      } else if (typeCrop == 2) {
        beans.setSeedsTypes(null);
        beans.setProductionEvents(new ProductionEvents(idCrop));
        beans.setStatus(true);
        session.saveOrUpdate(beans);
      } else if (typeCrop == 3) {
        //                Cassavas ca = new Cassavas();
        //                ca.setIdCas(null);
        //                ca.setProductionEvents(pro);
      }

      LogEntities log = new LogEntities();
      log.setIdLogEnt(null);
      log.setIdEntityLogEnt(idEntSystem);
      log.setIdObjectLogEnt(sowing.getIdSow());
      log.setTableLogEnt("sowing");
      log.setDateLogEnt(new Date());
      log.setActionTypeLogEnt(action);
      session.saveOrUpdate(log);

      tx.commit();
      state = "success";
      if (action.equals("C")) {
        info = "La siembra ha sido agregada con exito";
        //                return "list";
      } else if (action.equals("M")) {
        info = "La siembra ha sido modificada con exito";
        //                return "list";
      }
      SfGuardUserDao sfDao = new SfGuardUserDao();
      SfGuardUser sfUser = sfDao.getUserByLogin(user.getCreatedBy(), user.getNameUserUsr(), "");
      GlobalFunctions.sendInformationCrop(idCrop, typeCrop, sfUser.getId());
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
      }
      e.printStackTrace();
      //            System.out.println("error->"+e.getMessage());
      state = "failure";
      info = "Fallo al momento de agregar una siembra";
    } catch (ParseException e) {

    } finally {
      session.close();
    }

    //        return ERROR;
    return "states";
  }
  /**
   * Encargado de guardar la informacion suministrada por el usuario para un riego
   *
   * @return Estado del proceso
   */
  public String saveData() {
    if (!usrDao.getPrivilegeUser(idUsrSystem, "crop/create")
        || !usrDao.getPrivilegeUser(idUsrSystem, "crop/modify")) {
      return BaseAction.NOT_AUTHORIZED;
    }
    String action = "";
    //        System.out.println("Entre a guardar la info");
    /*
     * Se evalua dependiendo a la accion realizada:
     * 1) create: Al momento de guardar un registro por primera ves
     * 2) modify: Al momento de modificar un registro
     * 3) delete: Al momento de borrar un registro
     */
    if (actExe.equals("create")) {
      action = "C";
    } else if (actExe.equals("modify")) {
      action = "M";
    }

    SessionFactory sessions = HibernateUtil.getSessionFactory();
    Session session = sessions.openSession();
    Transaction tx = null;

    try {
      tx = session.beginTransaction();

      String dmy = new SimpleDateFormat("yyyy-MM-dd").format(irr.getDateIrr());
      Date dateIrr = new SimpleDateFormat("yyyy-MM-dd").parse(dmy);

      irr.setUseIrrigationIrr(true);
      irr.setProductionEvents(new ProductionEvents(idCrop));
      irr.setDateIrr(dateIrr);
      //            if (sowing.getChemicalsSowing().getIdCheSow()==-1) {
      //                sowing.setChemicalsSowing(null);
      //            }
      //
      //            if (sowing.getDoseUnits().getIdDosUni()==-1) {
      //                sowing.setDoseUnits(null);
      //            }
      irr.setStatus(true);
      session.saveOrUpdate(irr);

      LogEntities log = new LogEntities();
      log.setIdLogEnt(null);
      log.setIdEntityLogEnt(idEntSystem);
      log.setIdObjectLogEnt(irr.getIdIrr());
      log.setTableLogEnt("irrigation");
      log.setDateLogEnt(new Date());
      log.setActionTypeLogEnt(action);
      session.saveOrUpdate(log);
      tx.commit();
      state = "success";
      if (action.equals("C")) {
        info = "El riego ha sido agregado con exito";
        //                return "list";
      } else if (action.equals("M")) {
        info = "El riego ha sido modificado con exito";
        //                return "list";
      }
      HashMap prod = cropDao.findById(idCrop);
      Integer tyCro = Integer.parseInt(String.valueOf(prod.get("typeCrop")));
      SfGuardUserDao sfDao = new SfGuardUserDao();
      SfGuardUser sfUser = sfDao.getUserByLogin(user.getCreatedBy(), user.getNameUserUsr(), "");
      GlobalFunctions.sendInformationCrop(idCrop, tyCro, sfUser.getId());
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
      }
      e.printStackTrace();
      //            System.out.println("error->"+e.getMessage());
      state = "failure";
      info = "Fallo al momento de agregar un riego";
    } catch (ParseException e) {

    } finally {
      session.close();
    }

    //        return ERROR;
    return "states";
  }
  /**
   * Encargado de borrar la informacion de una finca apartir de su identificacion
   *
   * @param idFar: Identificacion de la finca
   * @return Estado del proceso
   */
  public String delete() {
    if (!usrDao.getPrivilegeUser(idUsrSystem, "farm/delete")) {
      return BaseAction.NOT_AUTHORIZED;
    }
    Integer idFar = 0;
    try {
      idFar = Integer.parseInt(this.getRequest().getParameter("idFar"));
    } catch (NumberFormatException e) {
      idFar = -1;
    }

    if (idFar == -1) {
      state = "failure";
      info = "Fallo al momento de obtener la informacion a borrar";
      return "states";
    }

    SessionFactory sessions = HibernateUtil.getSessionFactory();
    Session session = sessions.openSession();
    Transaction tx = null;

    try {
      tx = session.beginTransaction();
      Farms far = farDao.objectById(idFar);
      far.setStatus(false);
      session.saveOrUpdate(far);
      //            session.delete(far);
      //            farDao.delete(far);

      LogEntities log = new LogEntities();
      log.setIdLogEnt(null);
      log.setIdEntityLogEnt(idEntSystem); // Colocar el usuario registrado en el sistema
      log.setIdObjectLogEnt(far.getIdFar());
      log.setTableLogEnt("farms");
      log.setDateLogEnt(new Date());
      log.setActionTypeLogEnt("D");
      session.saveOrUpdate(log);
      //            logDao.save(log);

      BasicDBObject query = new BasicDBObject();
      query.put("InsertedId", "" + far.getIdFar());
      query.put("form_id", "3");

      MongoClient mongo = null;
      try {
        mongo = new MongoClient("localhost", 27017);
      } catch (UnknownHostException ex) {
        Logger.getLogger(ActionField.class.getName()).log(Level.SEVERE, null, ex);
      }
      DB db = mongo.getDB("ciat");
      DBCollection col = db.getCollection("log_form_records");
      WriteResult result = null;

      System.out.println("borro mongo");
      result = col.remove(query);

      if (result.getError() != null) {
        throw new HibernateException("");
      }
      mongo.close();

      FieldsDao fieDao = new FieldsDao();
      fieDao.deleteFieldsMongo(far.getIdFar());

      tx.commit();
      state = "success";
      info = "La finca ha sido borrada con exito";
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
      }
      e.printStackTrace();
      state = "failure";
      info = "Fallo al momento de borrar una finca";
    } finally {
      session.close();
    }

    return "states";
    //        return SUCCESS;
  }