/**
  * Returns the view info for all views in the given group in the given context.
  *
  * @param context
  * @param dbName
  * @return
  */
 private DataViewInfoData[] getDataViewInfoData(ResourceId context, String dbName) {
   DashboardInfo dinfo = model.getDashboardInfo(new DashboardId(context, dbName), true);
   if (dinfo == null) {
     return null;
   }
   List<DataViewInfoData> ret = new LinkedList<DataViewInfoData>();
   Dashboard db = dinfo.getDashboard();
   DataViewId[] views = db.getViews();
   if (views == null) {
     return null;
   }
   // find now query info on every member query
   DataViewId m;
   DataViewInfo dvinfo;
   for (int i = 0; i < views.length; i++) {
     m = views[i];
     if (context != null) {
       m = m.complete(context);
     }
     dvinfo = model.getDataViewInfo(m, true);
     if (dvinfo == null) {
       if (logger.isTraceEnabled()) {
         logger.error("Dataview " + m + " not found for dashboard " + db.getName());
       }
       continue;
     }
     ret.add(new DataViewInfoData(m.getContext(), dvinfo));
   }
   return (DataViewInfoData[]) ret.toArray(new DataViewInfoData[ret.size()]);
 }
  /**
   * @see
   *     com.ixora.rms.client.model.DashboardModelHelper#isDashboardReady(com.ixora.rms.internal.ResourceId,
   *     com.ixora.rms.repository.QueryGroup)
   */
  public boolean isDashboardReady(ResourceId context, Dashboard dashboard) {
    boolean ready = true;
    ResourceId[] counters = dashboard.getCounters();
    if (!Utils.isEmptyArray(counters)) {
      // check that all counters are present
      for (ResourceId c : counters) {
        if (context != null) {
          c = c.complete(context);
        }
        CounterInfo cinfo = model.getCounterInfo(c, true);
        if (cinfo == null) {
          return false;
        }
      }
    }

    // now check that all views are ready
    DataViewId[] views = dashboard.getViews();
    if (ready && !Utils.isEmptyArray(views)) {
      // find now query info on every member query
      for (DataViewId m : views) {
        if (context != null) {
          m = m.complete(context);
        }
        DataViewInfo dvinfo = model.getDataViewInfo(m, true);
        if (dvinfo == null) {
          return false;
        }
        if (!model
            .getQueryHelper()
            .isQueryReady(m.getContext(), dvinfo.getDataView().getQueryDef())) {
          return false;
        }
      }
    }
    return ready;
  }
  /** Applies only changes made to the current context. */
  private void applyChangesLocally() {
    // get all dashboards  to realize
    Collection<DashboardInfo> dashboards = getDashboardTableModel().getDashboardsToRealize();
    if (dashboards != null) {
      for (DashboardInfo dinfo : dashboards) {
        // register views with the query realizer
        DataViewId[] views = dinfo.getDashboard().getViews();
        if (!Utils.isEmptyArray(views)) {
          for (DataViewId view : views) {
            if (fContext != null) {
              view = view.complete(fContext);
            }
            // ask the locator for info on the required data view
            final SessionDataViewInfo dvInfo = this.fArtefactInfoLocator.getDataViewInfo(view);
            if (dvInfo == null) {
              if (logger.isTraceEnabled()) {
                logger.error("Couldn't find data view info for: " + view + ". Skipping...");
              }
              continue;
            }
            final DataViewId fv = view;
            // Note: this method is reading from the session model
            // and as a result it can only be used safely from
            // the event dispatching thread
            this.fViewContainer
                .getAppWorker()
                .runJobSynch(
                    new UIWorkerJobDefault(
                        fViewContainer.getAppFrame(),
                        Cursor.WAIT_CURSOR,
                        MessageRepository.get(
                            Msg.TEXT_REALIZING_DATAVIEW,
                            new String[] {dvInfo.getTranslatedName()})) {
                      public void work() throws Exception {
                        fQueryRealizer.realizeQuery(
                            fv.getContext(),
                            dvInfo.getDataView().getQueryDef(),
                            new QueryRealizer.Callback() {
                              public boolean acceptIncreaseInMonitoringLevel(
                                  List<ResourceInfo> counters) {
                                boolean ret =
                                    UIUtils.getBooleanYesNoInput(
                                        fViewContainer.getAppFrame(),
                                        MessageRepository.get(
                                            Msg.TITLE_CONFIRM_MONITORING_LEVEL_INCREASE),
                                        MessageRepository.get(
                                            Msg
                                                .TEXT_CONFIRM_MONITORING_LEVEL_INCREASE_FOR_DATA_VIEW,
                                            new String[] {dvInfo.getTranslatedName()}));
                                if (!ret) {
                                  // undo changes
                                  fSessionData
                                      .getDataViewHelper()
                                      .rollbackDataView(fv.getContext(), fv.getName());
                                }
                                return ret;
                              }
                            });
                      }

                      public void finished(Throwable ex) {}
                    });
          }
        }
        // register counters with the query realizer
        // for every counter create a query and register it
        ResourceId[] counters = dinfo.getDashboard().getCounters();
        if (!Utils.isEmptyArray(counters)) {
          for (ResourceId counter : counters) {
            if (fContext != null) {
              counter = counter.complete(fContext);
            }
            final SingleCounterQueryDef query = new SingleCounterQueryDef(counter, null, null);
            final ResourceId counterContext = counter.getSubResourceId(ResourceId.ENTITY);

            // add query to the model
            fSessionData.getQueryHelper().addQuery(counterContext, query);

            String translatedCounterName = counter.getCounterId().toString();
            // ask the locator for info on this counter
            SessionResourceInfo rInfo = this.fArtefactInfoLocator.getResourceInfo(counter);
            if (rInfo != null && rInfo.getCounterInfo() != null) {
              translatedCounterName = rInfo.getCounterInfo().getTranslatedName();
            }
            final String finalTranslatedCounterName = translatedCounterName;
            final ResourceId fc = counter;
            // Note: this method is reading from the session model
            // and as a result it can only be used safely from
            // the event dispatching thread
            this.fViewContainer
                .getAppWorker()
                .runJobSynch(
                    new UIWorkerJobDefault(
                        fViewContainer.getAppFrame(),
                        Cursor.WAIT_CURSOR,
                        MessageRepository.get(
                            Msg.TEXT_REALIZING_DATAVIEW, new String[] {translatedCounterName})) {
                      public void work() throws Exception {
                        fQueryRealizer.realizeQuery(
                            counterContext,
                            query,
                            new QueryRealizer.Callback() {
                              public boolean acceptIncreaseInMonitoringLevel(
                                  List<ResourceInfo> counters) {
                                boolean ret =
                                    UIUtils.getBooleanYesNoInput(
                                        fViewContainer.getAppFrame(),
                                        MessageRepository.get(
                                            Msg.TITLE_CONFIRM_MONITORING_LEVEL_INCREASE),
                                        MessageRepository.get(
                                            Msg.TEXT_CONFIRM_MONITORING_LEVEL_INCREASE_FOR_COUNTER,
                                            new String[] {finalTranslatedCounterName}));
                                if (!ret) {
                                  // undo changes
                                  fSessionData.getCounterHelper().rollbackCounter(fc, true);
                                }
                                return ret;
                              }
                            });
                      }

                      public void finished(Throwable ex) {
                        if (ex != null) {
                          UIExceptionMgr.userException(ex);
                        }
                      }
                    });
          }
        }
      }
    }

    // get all dashboards to unrealize
    dashboards = getDashboardTableModel().getDashboardsToUnRealize();
    if (dashboards != null) {
      for (DashboardInfo dinfo : dashboards) {
        // unregister views with the query realizer
        DataViewId[] views = dinfo.getDashboard().getViews();
        // get views
        if (!Utils.isEmptyArray(views)) {
          for (DataViewId view : views) {
            if (fContext != null) {
              view = view.complete(fContext);
            }
            // ask the locator for info on the required data view
            String viewTranslatedName = view.getName();
            final SessionDataViewInfo dvInfo = this.fArtefactInfoLocator.getDataViewInfo(view);
            if (dvInfo == null) {
              if (logger.isTraceEnabled()) {
                logger.error("Couldn't find data view info for: " + view);
              }
            } else {
              viewTranslatedName = dvInfo.getTranslatedName();
            }
            final DataViewId fv = view;
            // Note: this method is reading from the session model
            // and as a result it can only be used safely from
            // the event dispatching thread
            this.fViewContainer
                .getAppWorker()
                .runJobSynch(
                    new UIWorkerJobDefault(
                        fViewContainer.getAppFrame(),
                        Cursor.WAIT_CURSOR,
                        MessageRepository.get(
                            Msg.TEXT_REALIZING_DATAVIEW, new String[] {viewTranslatedName})) {
                      public void work() throws Exception {
                        QueryId qid = new QueryId(fv.getContext(), fv.getName());
                        fQueryRealizer.unrealizeQuery(qid, false);
                      }

                      public void finished(Throwable ex) {
                        if (ex != null) {
                          UIExceptionMgr.userException(ex);
                        }
                      }
                    });
          }

          // unregister counters with the query realizer
          ResourceId[] counters = dinfo.getDashboard().getCounters();
          if (!Utils.isEmptyArray(counters)) {
            for (ResourceId counter : counters) {
              if (fContext != null) {
                counter = counter.complete(fContext);
              }
              final ResourceId counterContext = counter.getSubResourceId(ResourceId.ENTITY);
              String translatedCounterName = counter.getCounterId().toString();
              // ask the locator for info on this counter
              SessionResourceInfo rInfo = this.fArtefactInfoLocator.getResourceInfo(counter);
              if (rInfo != null && rInfo.getCounterInfo() != null) {
                translatedCounterName = rInfo.getCounterInfo().getTranslatedName();
              }
              final ResourceId finalCounter = counter;
              // Note: this method is reading from the session model
              // and as a result it can only be used safely from
              // the event dispatching thread
              this.fViewContainer
                  .getAppWorker()
                  .runJobSynch(
                      new UIWorkerJobDefault(
                          fViewContainer.getAppFrame(),
                          Cursor.WAIT_CURSOR,
                          MessageRepository.get(
                              Msg.TEXT_REALIZING_DATAVIEW, new String[] {translatedCounterName})) {
                        public void work() throws Exception {
                          QueryId queryId =
                              new QueryId(counterContext, finalCounter.getCounterId().toString());
                          fQueryRealizer.unrealizeQuery(queryId, false);
                        }

                        public void finished(Throwable ex) {
                          if (ex != null) {
                            UIExceptionMgr.userException(ex);
                          }
                        }
                      });
            }
          }

          String dashboardName = dinfo.getDashboard().getName();
          fSessionData
              .getDashboardHelper()
              .setDashboardFlag(ArtefactInfo.ENABLED, fContext, dashboardName, false, true);
        }
      }
    }
    fSessionData.getDashboardHelper().recalculateDashboardsStatus(fContext);
    getDashboardTableModel().fireTableDataChanged();
    fActionApply.setEnabled(false);
    fActionCancel.setEnabled(false);
  }
  // the behaviour is as follows:
  // if the dashboard is not commited, the state will not be changed
  // else the state of the dasboard will be updated only if there is at least
  // one view already in the session model that belongs to this dashboard and
  // it is not enabled
  public void recalculateDashboardsStatus(ResourceId context) {
    ArtefactInfoContainerImpl acimpl = model.getArtefactContainerImplForResource(context, true);
    if (acimpl == null) {
      if (logger.isTraceEnabled()) {
        logger.error("Couldn't find container for: " + context);
      }
      return;
    }
    Collection<DashboardInfoImpl> cs = acimpl.getDashboardInfoImpl();
    if (cs == null) {
      return;
    }

    for (DashboardInfoImpl dinfo : cs) {
      if (dinfo.isCommitted()) {
        Dashboard db = dinfo.getDashboard();
        // flags to update
        boolean enabled = dinfo.getFlag(DashboardInfo.ENABLED);
        boolean plotted = dinfo.getFlag(DashboardInfo.ACTIVATED);
        boolean committed = dinfo.isCommitted();

        // check counters
        ResourceId[] counters = db.getCounters();
        if (!Utils.isEmptyArray(counters)) {
          // disable this dashboard only if one of it's counters
          // exists in the model and it's disabled
          for (ResourceId c : counters) {
            if (context != null) {
              c = c.complete(context);
            }
            CounterInfo cinfo = model.getCounterInfo(c, false);
            if (cinfo == null) {
              if (logger.isTraceEnabled()) {
                logger.error("Couldn't find counter: " + c);
              }
              break;
            }
            if (!cinfo.getFlag(CounterInfo.ENABLED)) {
              enabled = false;
            }
            if (!cinfo.getFlag(CounterInfo.ACTIVATED)) {
              plotted = false;
            }
            if (!cinfo.isCommitted()) {
              committed = false;
            }
          }
        }

        // check data views
        DataViewId[] views = db.getViews();
        if (!Utils.isEmptyArray(views)) {
          // disable this dashboard only if one of it's queries
          // exists in the model and it's disabled

          // find now info on every member
          DataViewId m;
          DataViewInfo dvinfo;
          for (int i = 0; i < views.length; i++) {
            m = views[i];
            if (context != null) {
              m = m.complete(context);
            }
            // refresh data views first
            model.getDataViewHelper().recalculateDataViewsStatus(m.getContext());
            dvinfo = model.getDataViewInfo(m, false);
            if (dvinfo == null) {
              // this query no longer exists...
              // ignore it with a warning in logs
              if (logger.isInfoEnabled()) {
                logger.error(
                    "Couldn't find view info for: "
                        + m
                        + ". Dashboard "
                        + dinfo.getTranslatedName()
                        + " will be incomplete.");
              }
              break;
            }
            // query exists and it will contribute to the state
            // of this dashboard
            if (!dvinfo.getFlag(QueryInfo.ENABLED)) {
              enabled = false;
            }
            if (!dvinfo.getFlag(QueryInfo.ACTIVATED)) {
              plotted = false;
            }
            if (!dvinfo.isCommitted()) {
              committed = false;
            }
          }
        }

        dinfo.setFlag(DashboardInfo.ENABLED, enabled);
        dinfo.setFlag(DashboardInfo.ACTIVATED, plotted);
        if (committed) {
          dinfo.commit();
        }
      } else {
        // just commit it
        dinfo.commit();
      }
    }
  }