public void OnSelectHost() {
    MoveHost model = (MoveHost) getWindow();

    if (model.getProgress() != null) {
      return;
    }

    if (!model.Validate()) {
      return;
    }

    model.setSelectedHosts(new java.util.ArrayList<VDS>());
    for (EntityModel a : Linq.<EntityModel>Cast(model.getItems())) {
      if (a.getIsSelected()) {
        model.getSelectedHosts().add((VDS) a.getEntity());
      }
    }

    VDSGroup cluster = (VDSGroup) model.getCluster().getSelectedItem();

    java.util.ArrayList<VdcActionParametersBase> paramerterList =
        new java.util.ArrayList<VdcActionParametersBase>();
    for (VDS host : model.getSelectedHosts()) {
      // Try to change host's cluster as neccessary.
      if (host.getvds_group_id() != null && !host.getvds_group_id().equals(cluster.getId())) {
        paramerterList.add(new ChangeVDSClusterParameters(cluster.getId(), host.getId()));
      }
    }
    model.StartProgress(null);
    Frontend.RunMultipleAction(
        VdcActionType.ChangeVDSCluster,
        paramerterList,
        new IFrontendMultipleActionAsyncCallback() {
          @Override
          public void Executed(FrontendMultipleActionAsyncResult result) {

            ClusterGuideModel clusterGuideModel = (ClusterGuideModel) result.getState();
            java.util.ArrayList<VDS> hosts =
                ((MoveHost) clusterGuideModel.getWindow()).getSelectedHosts();
            java.util.ArrayList<VdcReturnValueBase> retVals =
                (java.util.ArrayList<VdcReturnValueBase>) result.getReturnValue();
            if (retVals != null && hosts.size() == retVals.size()) {
              int i = 0;
              for (VDS selectedHost : hosts) {
                if (selectedHost.getstatus() == VDSStatus.PendingApproval
                    && retVals.get(i) != null
                    && retVals.get(i).getSucceeded()) {
                  Frontend.RunAction(
                      VdcActionType.ApproveVds, new ApproveVdsParameters(selectedHost.getId()));
                }
              }
              i++;
            }
            clusterGuideModel.getWindow().StopProgress();
            clusterGuideModel.Cancel();
            clusterGuideModel.PostAction();
          }
        },
        this);
  }
  @Override
  protected void PostDiscoverTargets(java.util.ArrayList<SanTargetModel> newItems) {
    super.PostDiscoverTargets(newItems);

    InitializeItems(null, newItems);

    // Remember all discovered targets.
    lastDiscoveredTargets.clear();
    lastDiscoveredTargets.addAll(newItems);
  }
 private String AvailableName(java.util.ArrayList<String> list) {
   String retVal = getCommonName();
   java.util.ArrayList<Integer> notAvialbleNumberList = new java.util.ArrayList<Integer>();
   String temp;
   for (String str : list) {
     temp = str.replace(getCommonName(), "");
     if (StringHelper.isNullOrEmpty(temp)) {
       temp = "0";
     }
     int tempInt = 0;
     RefObject<Integer> tempRef_tempInt = new RefObject<Integer>(tempInt);
     boolean tempVar = IntegerCompat.TryParse(temp, tempRef_tempInt);
     tempInt = tempRef_tempInt.argvalue;
     if (tempVar) {
       notAvialbleNumberList.add(tempInt);
     }
   }
   Collections.sort(notAvialbleNumberList);
   int i = 0;
   for (i = 0; i < notAvialbleNumberList.size(); i++) {
     if (notAvialbleNumberList.get(i) == i) {
       continue;
     }
     break;
   }
   if (i > 0) {
     retVal = getCommonName() + (new Integer(i)).toString();
   }
   return retVal;
 }
  public void SelectHost() {
    java.util.ArrayList<VDSGroup> clusters = new java.util.ArrayList<VDSGroup>();
    clusters.add(getEntity());

    MoveHost model = new MoveHost();
    model.setTitle("Select Host");
    model.setHashName("select_host");
    setWindow(model);
    model.getCluster().setItems(clusters);
    model.getCluster().setSelectedItem(Linq.FirstOrDefault(clusters));
    model.getCluster().setIsAvailable(false);

    UICommand tempVar = new UICommand("OnSelectHost", this);
    tempVar.setTitle("OK");
    tempVar.setIsDefault(true);
    model.getCommands().add(tempVar);
    UICommand tempVar2 = new UICommand("Cancel", this);
    tempVar2.setTitle("Cancel");
    tempVar2.setIsCancel(true);
    model.getCommands().add(tempVar2);
  }
  public java.util.ArrayList<LunModel> getAddedLuns() {
    java.util.ArrayList<LunModel> luns = new java.util.ArrayList<LunModel>();
    if (getIsGrouppedByTarget()) {
      java.util.List<SanTargetModel> items = (java.util.List<SanTargetModel>) getItems();
      for (SanTargetModel item : items) {
        for (LunModel lun : item.getLuns()) {
          if (lun.getIsSelected()
              && !lun.getIsIncluded()
              && Linq.FirstOrDefault(luns, new Linq.LunPredicate(lun)) == null) {
            luns.add(lun);
          }
        }
      }
    } else {
      java.util.List<LunModel> items = (java.util.List<LunModel>) getItems();
      for (LunModel lun : items) {
        if (lun.getIsSelected()
            && !lun.getIsIncluded()
            && Linq.FirstOrDefault(luns, new Linq.LunPredicate(lun)) == null) {
          luns.add(lun);
        }
      }
    }

    return luns;
  }
  /** Creates model items from the provided list of business entities. */
  public void ApplyData(java.util.List<LUNs> source, boolean isIncluded) {
    java.util.ArrayList<LunModel> newItems = new java.util.ArrayList<LunModel>();

    for (LUNs a : source) {
      if (a.getLunType() == getType() || a.getLunType() == StorageType.UNKNOWN) {
        java.util.ArrayList<SanTargetModel> targets = new java.util.ArrayList<SanTargetModel>();
        for (storage_server_connections b : a.getLunConnections()) {
          SanTargetModel tempVar = new SanTargetModel();
          tempVar.setAddress(b.getconnection());
          tempVar.setPort(b.getport());
          tempVar.setName(b.getiqn());
          tempVar.setIsSelected(true);
          tempVar.setIsLoggedIn(true);
          tempVar.setLuns(new ObservableCollection<LunModel>());
          SanTargetModel model = tempVar;
          model.getLoginCommand().setIsExecutionAllowed(false);

          targets.add(model);
        }

        LunModel tempVar2 = new LunModel();
        tempVar2.setLunId(a.getLUN_id());
        tempVar2.setVendorId(a.getVendorId());
        tempVar2.setProductId(a.getProductId());
        tempVar2.setSerial(a.getSerial());
        tempVar2.setMultipathing(a.getPathCount());
        tempVar2.setTargets(targets);
        tempVar2.setSize(a.getDeviceSize());
        tempVar2.setIsAccessible(a.getAccessible());
        tempVar2.setIsIncluded(isIncluded);
        tempVar2.setIsSelected(isIncluded);
        LunModel lun = tempVar2;
        newItems.add(lun);

        // Remember included LUNs to prevent their removal while updating items.
        if (isIncluded) {
          includedLUNs.add(lun);
        }
      }
    }

    InitializeItems(newItems, null);
    ProposeDiscover();
  }
  @Override
  protected void Update() {
    lastDiscoveredTargets.clear();

    super.Update();
  }
  private void UpdateOptions() {
    getCompulsoryActions().clear();
    getOptionalActions().clear();

    if (getEntity() != null) {
      storage_pool dataCenter = null;
      if (getEntity().getstorage_pool_id() != null) {
        dataCenter = DataProvider.GetDataCenterById(getEntity().getstorage_pool_id().getValue());
      }
      if (dataCenter == null || dataCenter.getstorage_pool_type() != StorageType.LOCALFS) {
        // Add host action.
        UICommand addHostAction = new UICommand("AddHost", this);

        // 				var hosts = DataProvider.GetHostListByCluster(Entity.name)
        // 					.Skip(1)
        // 					.ToList();
        java.util.ArrayList<VDS> hosts = DataProvider.GetHostListByCluster(getEntity().getname());
        if (hosts.size() > 1) {
          hosts.remove(0);
        }

        if (hosts.isEmpty()) {
          addHostAction.setTitle(ClusterConfigureHostsAction);
          getCompulsoryActions().add(addHostAction);
        } else {
          addHostAction.setTitle(ClusterAddAnotherHostAction);
          getOptionalActions().add(addHostAction);
        }
        if (getEntity().getstorage_pool_id() == null) {
          addHostAction.setIsExecutionAllowed(false);
          addHostAction
              .getExecuteProhibitionReasons()
              .add("The Cluster isn't attached to a Data Center");
          return;
        }
        java.util.ArrayList<VDSGroup> clusters =
            DataProvider.GetClusterList((Guid) getEntity().getstorage_pool_id());
        Version minimalClusterVersion = Linq.GetMinVersionByClusters(clusters);
        java.util.ArrayList<VDS> availableHosts = new java.util.ArrayList<VDS>();
        for (VDS vds : DataProvider.GetHostList()) {
          if ((!Linq.IsHostBelongsToAnyOfClusters(clusters, vds))
              && (vds.getstatus() == VDSStatus.Maintenance
                  || vds.getstatus() == VDSStatus.PendingApproval)
              && (vds.getVersion().getFullVersion() == null
                  || Extensions.GetFriendlyVersion(vds.getVersion().getFullVersion())
                          .compareTo(minimalClusterVersion)
                      >= 0)) {
            availableHosts.add(vds);
          }
        }
        // Select host action.
        UICommand selectHostAction = new UICommand("SelectHost", this);

        if (availableHosts.size() > 0 && clusters.size() > 0) {
          if (hosts.isEmpty()) {
            selectHostAction.setTitle(SelectHostsAction);
            getCompulsoryActions().add(selectHostAction);
          } else {
            selectHostAction.setTitle(SelectHostsAction);
            getOptionalActions().add(selectHostAction);
          }
        }
      } else {
        UICommand tempVar = new UICommand("AddHost", this);
        tempVar.setTitle(ClusterAddAnotherHostAction);
        UICommand addHostAction = tempVar;
        UICommand tempVar2 = new UICommand("SelectHost", this);
        tempVar2.setTitle(SelectHostsAction);
        UICommand selectHost = tempVar2;
        VDS host = DataProvider.GetLocalStorageHost(dataCenter.getname());
        if (host != null) {
          addHostAction.setIsExecutionAllowed(false);
          selectHost.setIsExecutionAllowed(false);
          String hasHostReason =
              "This Cluster belongs to a Local Data Center which already contain a Host";
          addHostAction.getExecuteProhibitionReasons().add(hasHostReason);
          selectHost.getExecuteProhibitionReasons().add(hasHostReason);
        }
        getCompulsoryActions().add(addHostAction);
        getOptionalActions().add(selectHost);
      }
    }
  }
  public void SetDefaultNames(VDS host, RefObject<String> message) {
    message.argvalue = null;
    setCommonName(StringFormat.format("%1$s-Local", host.getvds_name().replace('.', '-')));
    storage_pool candidate = null;

    // selecet all possible DCs
    VdcQueryReturnValue returnValue =
        Frontend.RunQuery(
            VdcQueryType.Search,
            new SearchParameters(
                StringFormat.format("DataCenter: name=%1$s", getCommonName() + "*"),
                SearchType.StoragePool));

    java.util.ArrayList<storage_pool> dataCenterList = new java.util.ArrayList<storage_pool>();
    java.util.ArrayList<VDSGroup> clusterList = null;
    if (returnValue != null && returnValue.getSucceeded() && returnValue.getReturnValue() != null) {
      dataCenterList =
          Linq.<storage_pool>Cast(
              (java.util.ArrayList<IVdcQueryable>) returnValue.getReturnValue());
    }
    // check if current settings suitable for local setup (in case just SD creation failed -
    // re-using the same setup)
    boolean useCurrentSettings = false;
    if (host.getstorage_pool_id() != null) {
      storage_pool tempCandidate = DataProvider.GetDataCenterById(host.getstorage_pool_id());
      if (IsLocalDataCenterEmpty(tempCandidate)) {
        candidate = tempCandidate;
        useCurrentSettings = true;
      } else {
        if (tempCandidate != null && tempCandidate.getstorage_pool_type() == StorageType.LOCALFS) {
          message.argvalue =
              "Note: Local Storage is already configured for this Host. The Host belongs to "
                  + host.getstorage_pool_name()
                  + " with local Storage Domain. If OK is clicked - this Host will be moved to a new Data Center, and a new Local Storage Domain will be created. Hit Cancel to abort the operation.";
        }
      }
    }
    // check if there is other DC suitable for re-use
    if (candidate == null) {
      for (storage_pool dataCenter : dataCenterList) {
        // need to check if the new DC is without host.
        if (IsLocalDataCenterEmpty(dataCenter)
            && DataProvider.GetLocalStorageHost(dataCenter.getname()) == null) {
          candidate = dataCenter;
          break;
        }
      }
    }
    java.util.ArrayList<String> listNames = new java.util.ArrayList<String>();
    // in case we found a suitable candidte for re-use:
    if (candidate != null) {
      getDataCenter().setDataCenterId(candidate.getId());
      getDataCenter().getName().setEntity(candidate.getname());
      getDataCenter().getDescription().setEntity(candidate.getdescription());
      Version compVersion = candidate.getcompatibility_version();
      getDataCenter().getVersion().setSelectedItem(compVersion);
      getCluster().getVersion().setSelectedItem(compVersion);
      setDontCreateDataCenter(true);
      // if we use current settings there is no need to create cluster.
      if (useCurrentSettings) {
        getCluster().setClusterId(host.getvds_group_id().getValue());
        getCluster().getName().setEntity(host.getvds_group_name());
        VDSGroup cluster = DataProvider.GetClusterById(host.getvds_group_id().getValue());
        if (cluster != null) {
          getCluster().getDescription().setEntity(cluster.getdescription());
          ServerCpu tempVar = new ServerCpu();
          tempVar.setCpuName(cluster.getcpu_name());
          getCluster().getCPU().setSelectedItem(tempVar);
        }
        setDontCreateCluster(true);
        setDontChangeHostCluster(true);
      }
      // use differnt cluster
      else {
        // check the DC cluster list (for re-use)
        clusterList = DataProvider.GetClusterList(candidate.getId());
        // no clusters avilable - pick up new name.
        if (clusterList.isEmpty()) {
          java.util.ArrayList<VDSGroup> listClusters = DataProvider.GetClusterList();
          listNames = new java.util.ArrayList<String>();
          for (VDSGroup cluster : listClusters) {
            listNames.add(cluster.getname());
          }
          getCluster().getName().setEntity(AvailableName(listNames));
        } else {
          // use the DC cluster.
          getCluster().setClusterId(clusterList.get(0).getId());
          getCluster().getName().setEntity(clusterList.get(0).getname());
          getCluster().getDescription().setEntity(clusterList.get(0).getdescription());
          VDSGroup cluster = DataProvider.GetClusterById(getCluster().getClusterId().getValue());
          if (cluster != null) {
            ServerCpu tempVar2 = new ServerCpu();
            tempVar2.setCpuName(cluster.getcpu_name());
            getCluster().getCPU().setSelectedItem(tempVar2);
          }
          setDontCreateCluster(true);
          if (host.getvds_group_id().getValue().equals(getCluster().getClusterId())) {
            setDontChangeHostCluster(true);
          }
        }
      }
    } else {
      // didn't found DC to re-use, so we select new names:
      listNames = new java.util.ArrayList<String>();
      for (storage_pool storagePool : dataCenterList) {
        listNames.add(storagePool.getname());
      }
      getDataCenter().getName().setEntity(AvailableName(listNames));

      // Choose a Data Center version corresponding to the host.
      if (!StringHelper.isNullOrEmpty(host.getsupported_cluster_levels())) {
        // the supported_cluster_levels are sorted.
        String[] array = host.getsupported_cluster_levels().split("[,]", -1);
        Version maxCombindVersion = null;

        for (int i = 0; i < array.length; i++) {
          Version vdsVersion = new Version(array[i]);
          for (Version version :
              (java.util.List<Version>) getDataCenter().getVersion().getItems()) {
            if (version.equals(vdsVersion) && version.compareTo(maxCombindVersion) > 0) {
              maxCombindVersion = version;
            }
          }
        }
        if (maxCombindVersion != null) {
          getDataCenter().getVersion().setSelectedItem(maxCombindVersion);
          getCluster().getVersion().setSelectedItem(maxCombindVersion);
        }
      }

      listNames = new java.util.ArrayList<String>();
      if (clusterList == null) {
        clusterList = DataProvider.GetClusterList();
      }

      for (VDSGroup cluster : clusterList) {
        listNames.add(cluster.getname());
      }
      getCluster().getName().setEntity(AvailableName(listNames));
    }

    // Choose default CPU name to match host.
    if (host.getCpuName() != null && getCluster().getCPU().getSelectedItem() != null) {
      getCluster()
          .getCPU()
          .setSelectedItem(
              Linq.FirstOrDefault(
                  (java.util.List<ServerCpu>) getCluster().getCPU().getItems(),
                  new Linq.ServerCpuPredicate(host.getCpuName().getCpuName())));
    }
    // always choose a avialable storage name.
    java.util.ArrayList<storage_domains> listStorageDomains = DataProvider.GetStorageDomainList();
    listNames = new java.util.ArrayList<String>();
    for (storage_domains storageDomain : listStorageDomains) {
      listNames.add(storageDomain.getstorage_name());
    }
    getFormattedStorageName().setEntity(AvailableName(listNames));
  }