public class FeatureManagerUI {
  public static boolean enabled =
      !Constants.isUnix
          // && FeatureAvailability.ENABLE_PLUS()
          || System.getProperty("fm.ui", "0").equals("1");

  private static FeatureManager featman;

  private static VuzeMessageBox validatingBox;

  private static VuzeMessageBox entryWindow;

  private static FeatureManagerUIListener fml;

  public static void registerWithFeatureManager() {
    if (!enabled) {
      return;
    }
    AzureusCoreFactory.addCoreRunningListener(
        new AzureusCoreRunningListener() {

          public void azureusCoreRunning(AzureusCore core) {
            PluginInterface pi = core.getPluginManager().getDefaultPluginInterface();
            featman = pi.getUtilities().getFeatureManager();

            fml = new FeatureManagerUIListener(featman);
            featman.addListener(fml);
            Licence[] licences = featman.getLicences();
            for (Licence licence : licences) {
              fml.licenceAdded(licence);
            }

            UIManager ui_manager = pi.getUIManager();

            ui_manager.addUIListener(
                new UIManagerListener() {
                  public void UIDetached(UIInstance instance) {}

                  public void UIAttached(UIInstance instance) {
                    if (!(instance instanceof UISWTInstance)) {
                      return;
                    }

                    if (!Utils.isAZ2UI()) {
                      addFreeBurnUI();
                    }
                  }
                });
          }
        });
  }

  private static void addFreeBurnUI() {
    final MultipleDocumentInterface mdi = UIFunctionsManager.getUIFunctions().getMDI();
    MdiEntry existingEntry = mdi.getEntry(MultipleDocumentInterface.SIDEBAR_HEADER_DVD);
    if (existingEntry != null) {
      // abandon all hope, something already added DVD stuff
      return;
    }
    mdi.registerEntry(
        MultipleDocumentInterface.SIDEBAR_SECTION_BURN_INFO,
        new MdiEntryCreationListener() {
          public MdiEntry createMDiEntry(String id) {

            MdiEntry entryAbout =
                mdi.createEntryFromSkinRef(
                    MultipleDocumentInterface.SIDEBAR_HEADER_DVD,
                    MultipleDocumentInterface.SIDEBAR_SECTION_BURN_INFO,
                    "main.burn.ftux",
                    MessageText.getString("mdi.entry.about.dvdburn"),
                    null,
                    null,
                    false,
                    null);
            entryAbout.setImageLeftID("image.sidebar.dvdburn");
            entryAbout.setExpanded(true);

            entryAbout.addListener(
                new MdiEntryDropListener() {
                  public boolean mdiEntryDrop(MdiEntry entry, Object droppedObject) {
                    openTrialAskWindow();
                    return true;
                  }
                });

            MenuManager menuManager =
                PluginInitializer.getDefaultInterface().getUIManager().getMenuManager();
            MenuItem menuHide =
                menuManager.addMenuItem(
                    "Sidebar." + MultipleDocumentInterface.SIDEBAR_SECTION_BURN_INFO,
                    "popup.error.hide");
            menuHide.addListener(
                new MenuItemListener() {
                  public void selected(MenuItem menu, Object target) {
                    mdi.closeEntry(MultipleDocumentInterface.SIDEBAR_SECTION_BURN_INFO);
                  }
                });

            return entryAbout;
          }
        });

    mdi.addListener(
        new MdiEntryLoadedListener() {
          public void mdiEntryLoaded(MdiEntry entry) {
            if (!entry.getId().equals(MultipleDocumentInterface.SIDEBAR_HEADER_DVD)) {
              return;
            }
            MdiEntryVitalityImage addSub = entry.addVitalityImage("image.sidebar.subs.add");
            addSub.addListener(
                new MdiEntryVitalityImageListener() {
                  public void mdiEntryVitalityImage_clicked(int x, int y) {
                    openTrialAskWindow();
                  }
                });
          }
        });

    mdi.registerEntry(
        MultipleDocumentInterface.SIDEBAR_SECTION_PLUS,
        new MdiEntryCreationListener() {
          public MdiEntry createMDiEntry(String id) {
            String title =
                MessageText.getString(
                    FeatureManagerUI.hasFullLicence()
                        ? "mdi.entry.plus.full"
                        : "mdi.entry.plus.free");
            String placeBelow =
                mdi.getEntry(MultipleDocumentInterface.SIDEBAR_SECTION_WELCOME) == null
                    ? ""
                    : MultipleDocumentInterface.SIDEBAR_SECTION_WELCOME;

            MdiEntry entry =
                mdi.createEntryFromSkinRef(
                    MultipleDocumentInterface.SIDEBAR_HEADER_VUZE,
                    MultipleDocumentInterface.SIDEBAR_SECTION_PLUS,
                    "main.area.plus",
                    title,
                    null,
                    null,
                    true,
                    placeBelow);
            entry.setImageLeftID("image.sidebar.plus");
            return entry;
          }
        });
    if (ConfigurationChecker.isNewVersion()
        && !ConfigurationChecker.isNewInstall()
        && !hasFullLicence()) {
      SBC_PlusFTUX.setSourceRef("startup");
      mdi.showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_PLUS);
    }
  }

  public static void openTrialAskWindow() {
    VuzeMessageBox box =
        new VuzeMessageBox(
            MessageText.getString("dlg.try.trial.title"),
            MessageText.getString("dlg.try.trial.text"),
            new String[] {
              MessageText.getString("Button.turnon"), MessageText.getString("Button.cancel")
            },
            0);
    box.setButtonVals(
        new Integer[] {
          SWT.OK, SWT.CANCEL,
        });
    box.addResourceBundle(
        FeatureManagerUI.class, SkinPropertiesImpl.PATH_SKIN_DEFS, "skin3_dlg_register");
    box.setIconResource("image.burn.dlg.header");

    box.setListener(
        new VuzeMessageBoxListener() {
          public void shellReady(Shell shell, SWTSkinObjectContainer soExtra) {
            SWTSkin skin = soExtra.getSkin();
            String id = "dlg.register.trialask";
            SWTSkinObject so = skin.createSkinObject(id, id, soExtra);

            SWTSkinObjectText soLink = (SWTSkinObjectText) skin.getSkinObject("link", so);
            if (soLink != null) {
              soLink.addUrlClickedListener(
                  new SWTSkinObjectText_UrlClickedListener() {
                    public boolean urlClicked(URLInfo urlInfo) {
                      String url =
                          ConstantsVuze.getDefaultContentNetwork()
                              .getExternalSiteRelativeURL("plus_tos.start", true);
                      Utils.launch(url);
                      return true;
                    }
                  });
            }
          }
        });

    box.open(
        new UserPrompterResultListener() {
          public void prompterClosed(int result) {
            if (result == SWT.OK) {
              SimpleTimer.addEvent(
                  "createTrial",
                  SystemTime.getCurrentTime(),
                  new TimerEventPerformer() {
                    public void perform(TimerEvent event) {
                      createTrial();
                    }
                  });
            }
          }
        });
  }

  public static void createTrial() {
    try {
      Licence[] trial = featman.createLicences(new String[] {"dvdburn_trial"});
    } catch (Throwable e) {
      String s = "Creating Trial: " + Debug.getNestedExceptionMessage(e);
      new MessageBoxShell("Trial Error", s).open(null);
      Logger.log(new LogAlert(true, s, e));
    }
  }

  public static void openLicenceEntryWindow(final boolean trytwo, final String prefillWith) {
    if (!enabled) {
      return;
    }

    if (entryWindow != null) {
      return;
    }

    try {
      String tryNo = (trytwo ? "2" : "1");
      final SWTSkinObjectTextbox[] key = new SWTSkinObjectTextbox[1];
      entryWindow =
          new VuzeMessageBox(
              MessageText.getString("dlg.auth.title"),
              MessageText.getString("dlg.auth.enter.line.try." + tryNo),
              new String[] {
                MessageText.getString("Button.agree"), MessageText.getString("Button.cancel")
              },
              0);
      entryWindow.setButtonVals(
          new Integer[] {
            SWT.OK, SWT.CANCEL,
          });

      entryWindow.setSubTitle(MessageText.getString("dlg.auth.enter.subtitle.try." + tryNo));
      entryWindow.addResourceBundle(
          FeatureManagerUI.class, SkinPropertiesImpl.PATH_SKIN_DEFS, "skin3_dlg_register");
      entryWindow.setIconResource("image.vp");
      if (trytwo) {
        entryWindow.setTextIconResource("image.warn.big");
      }

      entryWindow.setListener(
          new VuzeMessageBoxListener() {
            public void shellReady(Shell shell, SWTSkinObjectContainer soExtra) {
              SWTSkin skin = soExtra.getSkin();
              skin.createSkinObject("dlg.register", "dlg.register", soExtra);

              SWTSkinObjectText link =
                  (SWTSkinObjectText) skin.getSkinObject("register-link", soExtra);
              link.setText(
                  MessageText.getString(
                      trytwo ? "dlg.auth.enter.link.try.2" : "dlg.auth.enter.link.try.1"));
              link.addUrlClickedListener(
                  new SWTSkinObjectText_UrlClickedListener() {
                    public boolean urlClicked(URLInfo urlInfo) {
                      if (trytwo) {
                        String url =
                            ConstantsVuze.getDefaultContentNetwork()
                                .getExternalSiteRelativeURL("upgrade.start", true);
                        Utils.launch(url);
                      } else {
                        SBC_PlusFTUX.setSourceRef("dlg-activation");

                        MultipleDocumentInterface mdi =
                            UIFunctionsManager.getUIFunctions().getMDI();
                        mdi.showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_PLUS);
                        entryWindow.close(-2);
                      }
                      return true;
                    }
                  });

              SWTSkinObjectText linkTOS =
                  (SWTSkinObjectText) skin.getSkinObject("tos-link", soExtra);
              if (linkTOS != null) {
                linkTOS.addUrlClickedListener(
                    new SWTSkinObjectText_UrlClickedListener() {
                      public boolean urlClicked(URLInfo urlInfo) {
                        String url =
                            ConstantsVuze.getDefaultContentNetwork()
                                .getExternalSiteRelativeURL("plus_tos.start", true);
                        Utils.launch(url);
                        return true;
                      }
                    });
              }

              key[0] = (SWTSkinObjectTextbox) skin.getSkinObject("key", soExtra);
              if (key[0] != null) {
                if (prefillWith != null) {
                  key[0].setText(prefillWith);
                } else if (!trytwo) {
                  licenceDetails details = getFullFeatureDetails();
                  if (details != null && details.state != Licence.LS_INVALID_KEY) {
                    key[0].setText(details.key);
                    if (key[0].getControl() instanceof Text) {
                      ((Text) key[0].getControl()).selectAll();
                    }
                    final SWTSkinObjectText soExpirey =
                        (SWTSkinObjectText) skin.getSkinObject("register-expirey");
                    if (soExpirey != null) {
                      key[0]
                          .getControl()
                          .addListener(
                              SWT.Modify,
                              new Listener() {
                                public void handleEvent(Event event) {
                                  soExpirey.setText("");
                                }
                              });
                      if (details.state == Licence.LS_CANCELLED) {
                        soExpirey.setText(MessageText.getString("dlg.auth.enter.cancelled"));
                      } else if (details.state == Licence.LS_REVOKED) {
                        soExpirey.setText(MessageText.getString("dlg.auth.enter.revoked"));
                      } else if (details.state == Licence.LS_ACTIVATION_DENIED) {
                        soExpirey.setText(MessageText.getString("dlg.auth.enter.denied"));
                      } else {
                        soExpirey.setText(
                            MessageText.getString(
                                "dlg.auth.enter.expiry",
                                new String[] {
                                  DisplayFormatters.formatCustomDateOnly(details.expirey)
                                }));
                      }
                    }
                  }
                }
              }
            }
          });

      entryWindow.open(
          new UserPrompterResultListener() {
            public void prompterClosed(int result) {
              entryWindow = null;
              if (result == SWT.OK) {
                try {
                  Licence licence = featman.addLicence(key[0].getText());
                  int initialState = licence.getState();
                  if (initialState == Licence.LS_AUTHENTICATED) {
                    if (!licence.isFullyInstalled()) {
                      fml.licenceAdded(licence); // open installing window
                    } else {
                      openLicenceSuccessWindow();
                    }
                  } else if (initialState == Licence.LS_PENDING_AUTHENTICATION) {
                    fml.licenceAdded(licence); // open validating window
                  } else if (initialState == Licence.LS_INVALID_KEY) {
                    openLicenceFailedWindow(initialState, key[0].getText());
                  } else if (initialState == Licence.LS_ACTIVATION_DENIED) {
                    openLicenceActivationDeniedWindow(licence);
                  } else if (initialState == Licence.LS_CANCELLED) {
                    openLicenceCancelledWindow(licence);
                  } else if (initialState == Licence.LS_REVOKED) {
                    openLicenceRevokedWindow(licence);
                  }
                } catch (Throwable e) {

                  String s = Debug.getNestedExceptionMessage(e);

                  MessageBoxShell mb =
                      new MessageBoxShell(SWT.ICON_ERROR | SWT.OK, "Licence Addition Error", s);

                  mb.open();

                  Logger.log(new LogAlert(true, LogAlert.AT_ERROR, "Adding Licence", e));
                }
              }
            }
          });
    } catch (Exception e) {
      entryWindow = null;
    }
  }

  public static void openLicenceSuccessWindow() {
    if (!enabled) {
      return;
    }

    if (hasFullLicence()) {
      openFullLicenceSuccessWindow();
    } else {
      openTrialLicenceSuccessWindow();
    }
  }

  /** @since 4.1.0.5 */
  private static void openTrialLicenceSuccessWindow() {
    final VuzeMessageBox box =
        new VuzeMessageBox(
            MessageText.getString("dlg.auth.trial.success.subtitle"),
            MessageText.getString("dlg.auth.trial.success.line1"),
            new String[] {
              MessageText.getString("Button.goLibrary"),
            },
            0);
    box.addResourceBundle(
        FeatureManagerUI.class, SkinPropertiesImpl.PATH_SKIN_DEFS, "skin3_dlg_register");
    box.setIconResource("image.burn.dlg.header");

    box.setListener(
        new VuzeMessageBoxListener() {
          public void shellReady(Shell shell, SWTSkinObjectContainer soExtra) {
            SWTSkin skin = soExtra.getSkin();
            skin.createSkinObject(
                "dlg.register.trial.success", "dlg.register.trial.success", soExtra);
          }
        });

    box.open(
        new UserPrompterResultListener() {
          public void prompterClosed(int result) {
            if (result == 0) {
              SBC_PlusFTUX.setSourceRef("dlg-trial-installed");

              MultipleDocumentInterface mdi = UIFunctionsManager.getUIFunctions().getMDI();
              mdi.showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_LIBRARY);
            }
          }
        });
  }

  private static void openFullLicenceSuccessWindow() {
    final VuzeMessageBox box =
        new VuzeMessageBox(
            MessageText.getString("dlg.auth.title"),
            MessageText.getString("dlg.auth.success.line1"),
            new String[] {
              MessageText.getString("Button.getstarted"),
            },
            0);
    box.setSubTitle(MessageText.getString("dlg.auth.success.subtitle"));
    box.addResourceBundle(
        FeatureManagerUI.class, SkinPropertiesImpl.PATH_SKIN_DEFS, "skin3_dlg_register");
    box.setIconResource("image.vp");

    box.setListener(
        new VuzeMessageBoxListener() {
          public void shellReady(Shell shell, SWTSkinObjectContainer soExtra) {
            SWTSkin skin = soExtra.getSkin();
            skin.createSkinObject("dlg.register.success", "dlg.register.success", soExtra);
          }
        });

    box.open(
        new UserPrompterResultListener() {
          public void prompterClosed(int result) {
            if (result == 0) {
              SBC_PlusFTUX.setSourceRef("dlg-plus-installed");

              MultipleDocumentInterface mdi = UIFunctionsManager.getUIFunctions().getMDI();
              mdi.showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_PLUS);
            }
          }
        });
  }

  public static void openLicenceRevokedWindow(final Licence licence) {
    final VuzeMessageBox box =
        new VuzeMessageBox(
            MessageText.getString("dlg.auth.revoked"),
            MessageText.getString("dlg.auth.revoked.line1"),
            new String[] {
              MessageText.getString("Button.close"),
            },
            0);
    box.addResourceBundle(
        FeatureManagerUI.class, SkinPropertiesImpl.PATH_SKIN_DEFS, "skin3_dlg_register");
    box.setIconResource("image.vp");
    box.setTextIconResource("image.warn.big");

    box.setListener(
        new VuzeMessageBoxListener() {
          public void shellReady(Shell shell, SWTSkinObjectContainer soExtra) {
            SWTSkin skin = soExtra.getSkin();
            SWTSkinObject so =
                skin.createSkinObject("dlg.register.revoked", "dlg.register.revoked", soExtra);

            SWTSkinObjectText soLink = (SWTSkinObjectText) skin.getSkinObject("link", so);
            if (soLink != null) {
              soLink.addUrlClickedListener(
                  new SWTSkinObjectText_UrlClickedListener() {
                    public boolean urlClicked(URLInfo urlInfo) {
                      String url =
                          ConstantsVuze.getDefaultContentNetwork()
                              .getExternalSiteRelativeURL(
                                  "licence_revoked.start?key=" + UrlUtils.encode(licence.getKey()),
                                  true);
                      Utils.launch(url);
                      return true;
                    }
                  });
            }
          }
        });

    box.open(null);
  }

  public static void openLicenceActivationDeniedWindow(final Licence licence) {
    final VuzeMessageBox box =
        new VuzeMessageBox(
            MessageText.getString("dlg.auth.denied"),
            MessageText.getString("dlg.auth.denied.line1"),
            new String[] {
              MessageText.getString("Button.close"),
            },
            0);
    box.addResourceBundle(
        FeatureManagerUI.class, SkinPropertiesImpl.PATH_SKIN_DEFS, "skin3_dlg_register");
    box.setIconResource("image.vp");
    box.setTextIconResource("image.warn.big");

    box.setListener(
        new VuzeMessageBoxListener() {
          public void shellReady(Shell shell, SWTSkinObjectContainer soExtra) {
            SWTSkin skin = soExtra.getSkin();
            SWTSkinObject so =
                skin.createSkinObject("dlg.register.denied", "dlg.register.denied", soExtra);

            SWTSkinObjectText soLink = (SWTSkinObjectText) skin.getSkinObject("link", so);
            if (soLink != null) {
              soLink.addUrlClickedListener(
                  new SWTSkinObjectText_UrlClickedListener() {
                    public boolean urlClicked(URLInfo urlInfo) {
                      String url =
                          ConstantsVuze.getDefaultContentNetwork()
                              .getExternalSiteRelativeURL(
                                  "licence_denied.start?key=" + UrlUtils.encode(licence.getKey()),
                                  true);
                      Utils.launch(url);
                      return true;
                    }
                  });
            }
          }
        });

    box.open(null);
  }

  public static void openLicenceCancelledWindow(final Licence licence) {
    final VuzeMessageBox box =
        new VuzeMessageBox(
            MessageText.getString("dlg.auth.cancelled"),
            MessageText.getString("dlg.auth.cancelled.line1"),
            new String[] {
              MessageText.getString("Button.close"),
            },
            0);
    box.addResourceBundle(
        FeatureManagerUI.class, SkinPropertiesImpl.PATH_SKIN_DEFS, "skin3_dlg_register");
    box.setIconResource("image.vp");
    box.setTextIconResource("image.warn.big");

    box.setListener(
        new VuzeMessageBoxListener() {
          public void shellReady(Shell shell, SWTSkinObjectContainer soExtra) {
            SWTSkin skin = soExtra.getSkin();
            SWTSkinObject so =
                skin.createSkinObject("dlg.register.cancelled", "dlg.register.cancelled", soExtra);
          }
        });

    box.open(null);
  }

  protected static void openLicenceFailedWindow(int licenceState, String code) {
    openLicenceEntryWindow(true, code);
  }

  public static void openLicenceValidatingWindow() {
    if (!enabled || validatingBox != null) {
      return;
    }

    validatingBox =
        new VuzeMessageBox(MessageText.getString("dlg.auth.validating.subtitle"), null, null, 0);
    validatingBox.addResourceBundle(
        FeatureManagerUI.class, SkinPropertiesImpl.PATH_SKIN_DEFS, "skin3_dlg_register");
    validatingBox.setIconResource("image.vp");

    validatingBox.setListener(
        new VuzeMessageBoxListener() {
          public void shellReady(Shell shell, SWTSkinObjectContainer soExtra) {
            SWTSkin skin = soExtra.getSkin();
            skin.createSkinObject("dlg.register.validating", "dlg.register.validating", soExtra);
          }
        });

    validatingBox.open(
        new UserPrompterResultListener() {
          public void prompterClosed(int result) {
            validatingBox = null;
          }
        });
  }

  public static void closeLicenceValidatingWindow() {
    if (validatingBox != null) {
      validatingBox.close(0);
      validatingBox = null;
    }
  }

  public static String getMode() {
    boolean isFull = hasFullLicence();
    boolean isTrial = hasFullBurn() && !isFull;
    return isFull ? "plus" : isTrial ? "trial" : "free";
  }

  public static boolean hasFullLicence() {
    if (featman == null) {
      // Debug.out("featman null");
      Set<String> featuresInstalled = UtilitiesImpl.getFeaturesInstalled();
      return featuresInstalled.contains("dvdburn");
    }

    boolean full = false;
    FeatureDetails[] featureDetails = featman.getFeatureDetails("dvdburn");
    // if any of the feature details are still valid, we have a full
    for (FeatureDetails fd : featureDetails) {
      int state = fd.getLicence().getState();
      if (state == Licence.LS_CANCELLED || state == Licence.LS_REVOKED) {
        continue;
      }
      long now = SystemTime.getCurrentTime();
      Long lValidUntil = (Long) fd.getProperty(FeatureDetails.PR_VALID_UNTIL);
      if (lValidUntil != null && lValidUntil.longValue() >= now) {
        full = true;
        break;
      }
      Long lValidOfflineUntil = (Long) fd.getProperty(FeatureDetails.PR_OFFLINE_VALID_UNTIL);
      if (lValidOfflineUntil != null && lValidOfflineUntil.longValue() >= now) {
        full = true;
        break;
      }
    }

    return full;
  }

  public static class licenceDetails {
    public licenceDetails(long expirey, String key, int state) {
      this.expirey = expirey;
      this.key = key;
      this.state = state;
    }

    long expirey;
    String key;
    int state;
  }

  public static licenceDetails getFullFeatureDetails() {
    if (featman == null) {
      Debug.out("featman null");
      return null;
    }

    FeatureDetails[] featureDetails = featman.getFeatureDetails("dvdburn");
    // if any of the feature details are still valid, we have a full
    for (FeatureDetails fd : featureDetails) {
      long now = SystemTime.getCurrentTime();
      Long lValidUntil = (Long) fd.getProperty(FeatureDetails.PR_VALID_UNTIL);
      if (lValidUntil != null && lValidUntil.longValue() >= now) {
        return new licenceDetails(
            lValidUntil.longValue(), fd.getLicence().getKey(), fd.getLicence().getState());
      }
      Long lValidOfflineUntil = (Long) fd.getProperty(FeatureDetails.PR_OFFLINE_VALID_UNTIL);
      if (lValidOfflineUntil != null && lValidOfflineUntil.longValue() >= now) {
        return new licenceDetails(
            lValidOfflineUntil.longValue(), fd.getLicence().getKey(), fd.getLicence().getState());
      }
    }

    Licence bestLicence = null;
    Licence[] licences = featman.getLicences();
    for (Licence licence : licences) {
      FeatureDetails[] details = licence.getFeatures();
      boolean isTrial = false;
      for (FeatureDetails fd : details) {
        Object property = fd.getProperty(FeatureDetails.PR_IS_TRIAL);
        if ((property instanceof Number) && ((Number) property).intValue() == 1) {
          isTrial = true;
          break;
        }
      }
      if (isTrial) {
        continue;
      }
      int state = licence.getState();
      if (state == Licence.LS_AUTHENTICATED) {
        bestLicence = licence;
        break;
      } else {
        bestLicence = licence;
      }
    }

    if (bestLicence != null) {
      return new licenceDetails(0, bestLicence.getKey(), bestLicence.getState());
    }

    return null;
  }

  public static boolean isTrialLicence(Licence licence) {
    if (featman == null) {
      return false;
    }

    // if any of the FeatureDetails is a trial, return true

    boolean trial = false;
    FeatureDetails[] featureDetails = licence.getFeatures();
    for (FeatureDetails fd : featureDetails) {
      trial = isTrial(fd);
      if (trial) {
        break;
      }
    }

    return trial;
  }

  public static boolean isTrial(FeatureDetails fd) {
    Long lIsTrial = (Long) fd.getProperty(FeatureDetails.PR_IS_TRIAL);
    return lIsTrial == null ? false : lIsTrial.longValue() != 0;
  }

  public static long getRemaining() {
    FeatureDetails[] featureDetails = featman.getFeatureDetails("dvdburn_trial");
    if (featureDetails == null) {
      return 0;
    }
    for (FeatureDetails fd : featureDetails) {
      long remainingUses = getRemainingUses(fd);
      if (remainingUses >= 0) {
        return remainingUses;
      }
    }
    return 0;
  }

  private static long getRemainingUses(FeatureDetails fd) {
    if (fd == null) {
      return 0;
    }
    Long lRemainingUses = (Long) fd.getProperty(FeatureDetails.PR_TRIAL_USES_REMAINING);
    long remainingUses = lRemainingUses == null ? -1 : lRemainingUses.longValue();
    return remainingUses;
  }

  /** @return */
  public static boolean hasFullBurn() {

    PluginInterface pi =
        PluginInitializer.getDefaultInterface().getPluginState().isInitialisationComplete()
            ? AzureusCoreFactory.getSingleton()
                .getPluginManager()
                .getPluginInterfaceByID("azburn_v")
            : null;
    if (pi == null) {
      // maybe not added yet.. use featman
      Set<String> featuresInstalled = UtilitiesImpl.getFeaturesInstalled();
      return featuresInstalled.contains("dvdburn_trial") && !featuresInstalled.contains("dvdburn");
    }
    return pi.getPluginState().isOperational();
  }
}
Example #2
0
public class BuddiesViewer extends SkinView {

  private static final boolean SHOW_ONLINE_STATUS =
      System.getProperty("az.buddy.show_online", "1").equals("1");

  public static final int none_active_mode = 0;

  public static final int edit_mode = 1;

  public static final int share_mode = 2;

  public static final int invite_mode = 3;

  public static final int add_buddy_mode = 4;

  public static final int disabled_mode = 5;

  private Composite avatarsPanel = null;

  private Composite parent = null;

  private SWTSkin skin = null;

  private int avatarHightLightBorder;

  private int avatarImageBorder;

  private Point avatarImageSize = null;

  private Point avatarNameSize = null;

  private Point avatarSize = null;

  private int hSpacing;

  private List avatarWidgets = new ArrayList();

  private boolean isShareMode = false;

  private boolean isEditMode = false;

  private boolean isAddBuddyMode = false;

  private boolean isEnabled = true;

  private Color textColor = null;

  private Color selectedTextColor = null;

  private Color textLinkColor = null;

  private Color imageBorderColor = null;

  private Color selectedColor = null;

  private Color highlightedColor = null;

  private SWTSkinObject soNoBuddies;

  private com.aelitis.azureus.ui.swt.shells.friends.SharePage sharePage;

  private List buddiesList;

  private boolean reorder_outstanding;

  private Chat chat;

  private Color colorFileDragBorder;

  private Color colorFileDragBG;

  private ScrolledComposite scrollable;

  public BuddiesViewer() {

    chat = new Chat();
    chat.addChatListener(
        new ChatListener() {
          public void newMessage(final VuzeBuddy from, final ChatMessage message) {
            final AvatarWidget avatarWidget = findWidget(from);
            if (avatarWidget != null) {
              avatarWidget.setChatDiscussion(chat.getChatDiscussionFor(from));
              BuddyPlugin plugin = VuzeBuddyManager.getBuddyPlugin();
              if (plugin != null) {
                BooleanParameter enabledNotifictions = plugin.getEnableChatNotificationsParameter();

                if (!message.isMe() && enabledNotifictions.getValue()) {
                  avatarWidget
                      .getControl()
                      .getDisplay()
                      .asyncExec(
                          new Runnable() {
                            public void run() {
                              boolean isVisible = true;
                              if (avatarsPanel != null) {
                                if (!avatarsPanel.isVisible()) {
                                  isVisible = false;
                                }
                                /*Shell mainShell = avatarsPanel.getShell();
                                boolean mVisible = mainShell.isVisible();
                                boolean mEnabled = mainShell.isEnabled();
                                boolean mGetEnabled = mainShell.getEnabled();
                                boolean isFC = mainShell.isFocusControl();
                                Shell activeShell = mainShell.getDisplay().getActiveShell();*/
                                if (avatarsPanel.getShell().getDisplay().getActiveShell() == null) {
                                  isVisible = false;
                                }
                              }
                              // boolean isVisible = BuddiesViewer.this.isEnabled();
                              // avatarWidget.isChatWindowVisible();
                              if (!isVisible) {

                                new MessageNotificationWindow(avatarWidget, message);

                                /*
                                 * KN: MessageNotificationWindow above should really be moved into requestUserAttention()
                                 * so it can be handled in a platform-specific way if need be
                                 */
                                UserAlerts.requestUserAttention(
                                    PlatformManager.USER_REQUEST_INFO, null);
                              }
                            }
                          });
                }
              }
            }
          }

          public void updatedChat(VuzeBuddy buddy) {
            final AvatarWidget avatarWidget = findWidget(buddy);
            if (avatarWidget != null) {
              avatarWidget.setChatDiscussion(chat.getChatDiscussionFor(buddy));
            }
          }
        });

    /*
     * backed this change out as the desired behaviour is to continue showing
     * buddies when logged out as all attempts to do something with buddy will
     * prompt for login
     *
    LoginInfoManager.getInstance().addListener(
    	new ILoginInfoListener()
    	{
    		public void
    		loginUpdate(
    			LoginInfo 	info,
    			boolean 	isNewLoginID )
    		{
    			Utils.execSWTThreadLater(0, new AERunnable() {
    				public void
    				runSupport()
    				{
    					boolean logged_in = LoginInfoManager.getInstance().isLoggedIn();

    					boolean show_no_buddies = avatarWidgets.size() < 1 || !logged_in;

    					showNoBuddiesPanel( show_no_buddies );
    				}
    			});
    		}
    	});
    	*/
  }

  public Object skinObjectInitialShow(SWTSkinObject skinObject, Object params) {
    skin = skinObject.getSkin();

    SWTSkinProperties properties = skin.getSkinProperties();
    colorFileDragBorder = properties.getColor("color.buddy.filedrag.bg.border");
    colorFileDragBG = properties.getColor("color.buddy.filedrag.bg");

    soNoBuddies = skin.getSkinObject("buddies-viewer-nobuddies-panel");

    SWTSkinObject viewer = skin.getSkinObject(SkinConstants.VIEWID_BUDDIES_VIEWER);

    if (null != viewer) {

      parent = (Composite) skinObject.getControl();
      parent.setBackgroundMode(SWT.INHERIT_FORCE);
      scrollable = new ScrolledComposite(parent, SWT.V_SCROLL);
      scrollable.setExpandHorizontal(true);
      scrollable.setExpandVertical(true);
      scrollable.setBackgroundMode(SWT.INHERIT_FORCE);
      scrollable.getVerticalBar().setIncrement(10);
      scrollable.getVerticalBar().setPageIncrement(65);

      FormData fd = new FormData();
      fd.top = new FormAttachment(0, 0);
      fd.bottom = new FormAttachment(100, 0);
      fd.left = new FormAttachment(0, 0);
      fd.right = new FormAttachment(100, 0);
      scrollable.setLayoutData(fd);

      avatarsPanel = new Composite(scrollable, SWT.NONE);
      avatarsPanel.setBackgroundMode(SWT.INHERIT_FORCE);
      scrollable.setContent(avatarsPanel);

      scrollable.addListener(
          SWT.Resize,
          new Listener() {

            public void handleEvent(Event event) {
              Rectangle r = scrollable.getClientArea();
              scrollable.setMinHeight(avatarsPanel.computeSize(r.width, SWT.DEFAULT).y);
            }
          });

      /*
       * Specify avatar dimensions and attributes before creating the avatars
       */
      textColor = parent.getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND);
      selectedTextColor = parent.getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT);
      textLinkColor = properties.getColor("color.links.hover");
      imageBorderColor = properties.getColor("color.buddy.bg.border");
      selectedColor = parent.getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION);
      highlightedColor = parent.getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW);

      avatarHightLightBorder = 0;
      avatarImageBorder = 1;
      hSpacing = 1;
      avatarImageSize = new Point(40, 40);
      avatarNameSize = new Point(60, 30);
      avatarSize = new Point(0, 0);
      avatarSize.x =
          Math.max(avatarNameSize.x, avatarImageSize.x)
              + (2 * (avatarHightLightBorder + avatarImageBorder));
      avatarSize.y =
          avatarNameSize.y
              + avatarImageSize.y
              + (2 * (avatarHightLightBorder + avatarImageBorder) + 6);

      fillBuddies(avatarsPanel);

      /* UNCOMMENT THIS SECTION TO REVERT TO A ROW LAYOUT*/
      //			RowLayout rLayout = new RowLayout(SWT.HORIZONTAL);
      //			rLayout.wrap = true;
      //			rLayout.spacing = hSpacing;
      //			avatarsPanel.setLayout(rLayout);

      // COMMENT THIS SECTION TO REVERT TO A ROW LAYOUT
      SimpleReorderableListLayout rLayout = new SimpleReorderableListLayout();
      rLayout.margin = hSpacing;
      rLayout.wrap = true;
      rLayout.center = true;
      avatarsPanel.setLayout(rLayout);

      avatarsPanel.pack();

      avatarsPanel.addMouseListener(
          new MouseAdapter() {
            public void mouseDown(MouseEvent e) {
              select(null, false, false);
            }
          });

      avatarsPanel.addMouseListener(
          new MouseAdapter() {
            public void mouseDown(MouseEvent e) {
              select(null, false, false);
            }
          });

      parent.layout();

      hookFAQLink();

      hookImageAction();
    }

    return null;
  }

  public boolean isEditMode() {
    return isEditMode;
  }

  public void setEditMode(boolean value) {
    if (isEditMode != value) {
      isEditMode = value;
      for (Iterator iterator = avatarWidgets.iterator(); iterator.hasNext(); ) {
        AvatarWidget widget = (AvatarWidget) iterator.next();
        widget.refreshVisual();
      }

      if (true == value) {
        setShareMode(false, null);
        setAddBuddyMode(false);
      }
    }
  }

  private void fillBuddies(Composite composite) {

    List buddies = getBuddies();

    showNoBuddiesPanel(buddies.size() == 0);

    for (Iterator iterator = buddies.iterator(); iterator.hasNext(); ) {
      VuzeBuddySWT vuzeBuddy = (VuzeBuddySWT) iterator.next();
      createBuddyControls(composite, vuzeBuddy);
    }
    composite.layout();
    Point size = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
    composite.setSize(size);
  }

  private void showNoBuddiesPanel(boolean value) {
    if (soNoBuddies != null && soNoBuddies.isVisible() != value) {
      soNoBuddies.setVisible(value);
    }
  }

  private AvatarWidget createBuddyControls(Composite composite, final VuzeBuddySWT vuzeBuddy) {
    AvatarWidget avatarWidget =
        new AvatarWidget(this, avatarSize, avatarImageSize, avatarNameSize, vuzeBuddy);
    avatarWidget.setBorderWidth(avatarHightLightBorder);
    avatarWidget.setTextColor(textColor);
    avatarWidget.setSelectedTextColor(selectedTextColor);
    avatarWidget.setTextLinkColor(textLinkColor);
    avatarWidget.setImageBorderColor(imageBorderColor);
    avatarWidget.setImageBorder(avatarImageBorder);
    avatarWidget.setSelectedColor(selectedColor);
    avatarWidget.setHighlightedColor(highlightedColor);

    /* UNCOMMENT THIS SECTION TO REVERT TO A ROW LAYOUT*/
    //		RowData rData = new RowData();
    //		rData.width = avatarSize.x;
    //		rData.height = avatarSize.y;
    //		avatarWidget.getControl().setLayoutData(rData);

    // COMMENT THIS SECTION TO REVERT TO A ROW LAYOUT
    SimpleReorderableListLayoutData rData = new SimpleReorderableListLayoutData();
    rData.width = avatarSize.x;
    rData.height = avatarSize.y;
    rData.position = (int) VuzeBuddyManager.getBuddyPosition(vuzeBuddy);
    avatarWidget.getControl().setLayoutData(rData);

    avatarWidgets.add(avatarWidget);

    chat.checkBuddy(vuzeBuddy);

    return avatarWidget;
  }

  /**
   * Returns whether the given <code>AvatarWidget</code> is fully visible in the view port of the
   * viewer
   */
  public boolean isFullyVisible(AvatarWidget avatarWidget) {
    if (null != avatarWidget
        && null != avatarWidget.getControl()
        && false == avatarWidget.getControl().isDisposed()) {

      Rectangle controlBounds = avatarWidget.getControl().getBounds();
      if (controlBounds.x + controlBounds.width
          < avatarsPanel.getBounds().width - avatarsPanel.getBounds().x) {
        return true;
      }
    }
    return false;
  }

  public void removeBuddy(final AvatarWidget widget) {
    Utils.execSWTThreadLater(
        0,
        new AERunnable() {
          public void runSupport() {
            avatarWidgets.remove(widget);
            widget.dispose(
                true,
                new AvatarWidget.AfterDisposeListener() {
                  public void disposed() {
                    avatarsPanel.setSize(avatarsPanel.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
                    if (avatarWidgets.size() < 1) {
                      showNoBuddiesPanel(true);
                    }
                  }
                });
          }
        });
  }

  public void removeBuddy(VuzeBuddy buddy) {
    AvatarWidget widget = findWidget(buddy);
    if (null != widget) {
      removeBuddy(widget);
    } else {
      Debug.out("Unknown VuzeBuddy; can not remove from viewer since we don't have it.");
    }
  }

  public void updateBuddy(final VuzeBuddy buddy) {
    if (buddy instanceof VuzeBuddySWT) {

      Utils.execSWTThreadLater(
          0,
          new AERunnable() {

            public void runSupport() {
              AvatarWidget widget = findWidget(buddy);
              if (null != widget) {
                widget.setVuzeBuddy((VuzeBuddySWT) buddy);
              } else {
                /*
                 * If not found yet then we create the avatar for it; this really should not happen
                 * but we'll handle it just in case
                 */
                addBuddy(buddy);
              }
            }
          });
    }
  }

  public void addBuddy(final VuzeBuddy buddy) {
    if (buddy instanceof VuzeBuddySWT) {
      Utils.execSWTThreadLater(
          0,
          new AERunnable() {
            public void runSupport() {
              AvatarWidget widget = findWidget(buddy);
              if (widget == null) {
                if (soNoBuddies != null) {
                  soNoBuddies.setVisible(false);
                }
                createBuddyControls(avatarsPanel, (VuzeBuddySWT) buddy);
                avatarsPanel.layout();
                Point size = avatarsPanel.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
                avatarsPanel.setSize(size);
              }
            }
          });

    } else {
      Debug.out("Wrong type VuzeBuddy... must be of type VuzeBuddySWT");
    }
  }

  private AvatarWidget findWidget(VuzeBuddy buddy) {
    if (null != buddy) {
      for (Iterator iterator = avatarWidgets.iterator(); iterator.hasNext(); ) {
        AvatarWidget widget = (AvatarWidget) iterator.next();
        if (null != widget.getVuzeBuddy()) {
          if (true == buddy.getLoginID().equals(widget.getVuzeBuddy().getLoginID())) {
            return widget;
          }
        }
      }
    }

    return null;
  }

  /**
   * Return a list of <code>VuzeBuddySWT</code> that are currently selected
   *
   * @return
   */
  public List getSelection() {
    List selected = new ArrayList();
    for (Iterator iterator = avatarWidgets.iterator(); iterator.hasNext(); ) {
      AvatarWidget widget = (AvatarWidget) iterator.next();
      if (true == widget.isSelected()) {
        selected.add(widget.getVuzeBuddy());
      }
    }
    return selected;
  }

  public void select(VuzeBuddySWT buddy, boolean value, boolean appendSelection) {

    if (null != buddy) {
      for (Iterator iterator = avatarWidgets.iterator(); iterator.hasNext(); ) {
        AvatarWidget widget = (AvatarWidget) iterator.next();
        if (true == buddy.equals(widget.getVuzeBuddy())) {
          widget.setSelected(value);
          if (true == appendSelection) {
            break;
          }
        } else if (false == appendSelection) {
          if (true == value) {
            if (widget.isSelected() != false) {
              widget.setSelected(false);
              widget.refreshVisual();
            }
          } else {
            widget.setSelected(false);
            widget.refreshVisual();
          }
        }
      }
    }
    /*
     * De-select all buddies if the given 'buddy' is null
     */
    else {
      for (Iterator iterator = avatarWidgets.iterator(); iterator.hasNext(); ) {
        AvatarWidget widget = (AvatarWidget) iterator.next();
        if (true == widget.isSelected()) {
          widget.setSelected(false);
          widget.refreshVisual();
        }
      }
    }
  }

  private void recomputeOrder(boolean delay) {

    if (delay) {

      synchronized (this) {
        if (reorder_outstanding) {

          return;
        }

        reorder_outstanding = true;

        new DelayedEvent(
            "BuddiesViewer:delayReorder",
            5 * 1000,
            new AERunnable() {
              public void runSupport() {
                synchronized (BuddiesViewer.this) {
                  reorder_outstanding = false;
                }

                recomputeOrder(false);
              }
            });

        return;
      }
    }

    Utils.execSWTThreadLater(
        0,
        new AERunnable() {
          public void runSupport() {

            /* UNCOMMENT THIS SECTION TO REVERT TO A ROW LAYOUT
            return;
            */

            // COMMENT THIS SECTION TO REVERT TO A ROW LAYOUT
            if (avatarsPanel.isDisposed()) return;

            final List buddies = VuzeBuddyManager.getAllVuzeBuddies();

            // Only sort by online status if we show it
            if (SHOW_ONLINE_STATUS) {
              Collections.sort(
                  buddies,
                  new Comparator() {
                    public int compare(Object o1, Object o2) {
                      VuzeBuddy v1 = (VuzeBuddy) o1;
                      VuzeBuddy v2 = (VuzeBuddy) o2;
                      int score = 0;
                      ChatDiscussion d1 = getChat().getChatDiscussionFor(v1);
                      ChatDiscussion d2 = getChat().getChatDiscussionFor(v2);
                      if (d1 != null && d1.getUnreadMessages() > 0) {
                        score -= 1;
                      }
                      if (d2 != null && d2.getUnreadMessages() > 0) {
                        score += 1;
                      }

                      if (score == 0) {
                        if (d1 != null && d1.getNbMessages() > 0) {
                          score -= 1;
                        }
                        if (d2 != null && d2.getNbMessages() > 0) {
                          score += 1;
                        }
                      }

                      if (score == 0) {
                        score -= v1.isOnline(true) ? 1 : 0;
                        score += v2.isOnline(true) ? 1 : 0;
                      }

                      return score;
                    }
                  });
            }

            boolean changed = false;
            for (int i = 0; i < buddies.size(); i++) {
              VuzeBuddy buddy = (VuzeBuddy) buddies.get(i);
              AvatarWidget widget = findWidget(buddy);
              if (widget != null) {
                Control control = widget.getControl();
                if (control != null && !control.isDisposed()) {
                  Object data = widget.getControl().getLayoutData();
                  if (data instanceof SimpleReorderableListLayoutData) {
                    SimpleReorderableListLayoutData rData =
                        (SimpleReorderableListLayoutData) widget.getControl().getLayoutData();
                    if (rData.position != i) {
                      rData.position = i;
                      changed = true;
                    }
                  }
                }
              }
            }
            if (changed) {
              avatarsPanel.layout();
            }
          }
        });
  }

  private List getBuddies() {

    /*
     * Add the listener only once at the beginning
     */
    if (null == buddiesList) {
      VuzeBuddyManager.addListener(
          new VuzeBuddyListener() {

            public void buddyRemoved(VuzeBuddy buddy) {
              removeBuddy(buddy);
              recomputeOrder(false);
            }

            public void buddyChanged(VuzeBuddy buddy) {
              updateBuddy(buddy);
              recomputeOrder(true);
            }

            public void buddyAdded(VuzeBuddy buddy, int position) {
              addBuddy(buddy);
              recomputeOrder(false);
            }

            public void buddyOrderChanged() {}
          },
          false);
    }

    buddiesList = VuzeBuddyManager.getAllVuzeBuddies();
    return buddiesList;
  }

  public Composite getControl() {
    return avatarsPanel;
  }

  public boolean isShareMode() {
    return isShareMode;
  }

  public void addAllToShare() {
    addToShare(avatarWidgets);
  }

  public void removeAllFromShare() {
    removeFromShare(avatarWidgets);
  }

  public void addToShare(List avatars) {

    for (Iterator iterator = avatars.iterator(); iterator.hasNext(); ) {
      Object object = (Object) iterator.next();
      if (object instanceof AvatarWidget) {
        addToShare((AvatarWidget) object);
      }
    }
  }

  public void addToShare(AvatarWidget widget) {
    /*if (null == sharePage) {
    	SkinView detailPanelView = SkinViewManager.getByClass(DetailPanel.class);
    	if (detailPanelView instanceof DetailPanel) {
    		DetailPanel detailPanel = ((DetailPanel) detailPanelView);
    		sharePage = (SharePage) detailPanel.getPage(SharePage.PAGE_ID);

    	} else {
    		throw new IllegalArgumentException(
    				"Oops.. looks like the DetailPanel skin is not properly initialized");
    	}
    }*/
    if (sharePage != null) {
      sharePage.addBuddy(widget.getVuzeBuddy());
    }
    widget.setSharedAlready(true);
  }

  public void removeFromShare(List avatars) {

    for (Iterator iterator = avatars.iterator(); iterator.hasNext(); ) {
      Object object = (Object) iterator.next();
      if (object instanceof AvatarWidget) {
        removeFromShare((AvatarWidget) object);
      }
    }
  }

  public void removeFromShare(AvatarWidget widget) {
    if (sharePage != null) {
      sharePage.removeBuddy(widget.getVuzeBuddy());
    }
    widget.setSharedAlready(false);
  }

  public void addToShare(VuzeBuddy buddy) {
    AvatarWidget widget = findWidget(buddy);
    if (null != widget) {
      if (false == widget.isSharedAlready()) {
        addToShare(widget);
      }
    }
  }

  public void addSelectionToShare() {

    for (Iterator iterator = avatarWidgets.iterator(); iterator.hasNext(); ) {
      AvatarWidget widget = (AvatarWidget) iterator.next();
      if (true == widget.isSelected()) {
        addToShare(widget);
      }
    }
  }

  public void removeFromShare(VuzeBuddy buddy) {

    if (null != buddy) {
      for (Iterator iterator = avatarWidgets.iterator(); iterator.hasNext(); ) {
        AvatarWidget widget = (AvatarWidget) iterator.next();
        if (null != widget.getVuzeBuddy()) {
          if (true == buddy.getLoginID().equals(widget.getVuzeBuddy().getLoginID())) {
            if (sharePage != null) {
              sharePage.removeBuddy(widget.getVuzeBuddy());
            }
            widget.setSharedAlready(false);
            break;
          }
        }
      }
    }
  }

  public void setShareMode(boolean isShareMode, SharePage sharePage) {

    this.sharePage = sharePage;

    if (this.isShareMode != isShareMode) {
      this.isShareMode = isShareMode;
      for (Iterator iterator = avatarWidgets.iterator(); iterator.hasNext(); ) {
        AvatarWidget widget = (AvatarWidget) iterator.next();
        if (false == isShareMode) {
          widget.setSharedAlready(false);
        }
        widget.refreshVisual();
      }

      if (true == isShareMode) {
        setEditMode(false);
        setAddBuddyMode(false);
      }
    }
  }

  public boolean isNonActiveMode() {
    return !isAddBuddyMode() && !isShareMode() && !isEditMode();
  }

  public boolean isAddBuddyMode() {
    return isAddBuddyMode;
  }

  public void setAddBuddyMode(boolean isAddBuddyMode) {
    this.isAddBuddyMode = isAddBuddyMode;
    /*
     * Turn off share mode when we enter add buddy flow
     */
    if (true == isAddBuddyMode) {
      setShareMode(false, null);
      setEditMode(false);
    }
  }

  public void setMode(int mode) {
    if (mode == none_active_mode) {
      setShareMode(false, null);
      setEditMode(false);
      setAddBuddyMode(false);
    } else if (mode == edit_mode) {
      setEditMode(true);
    } else if (mode == share_mode) {
      setShareMode(true, sharePage);
    } else if (mode == add_buddy_mode) {
      setAddBuddyMode(true);
    }

    if (mode == disabled_mode) {
      setEnabled(false);
    } else {
      setEnabled(true);
    }
  }

  public void hookFAQLink() {
    SWTSkinObject FAQObject = skin.getSkinObject("buddies-viewer-nobuddies-link");
    if (null != FAQObject) {
      SWTSkinButtonUtility FAQButton = new SWTSkinButtonUtility(FAQObject);
      FAQButton.addSelectionListener(
          new ButtonListenerAdapter() {
            public void pressed(
                SWTSkinButtonUtility buttonUtility, SWTSkinObject skinObject, int stateMask) {
              String url = Constants.URL_FAQ_BY_TOPIC_ENTRY + FAQTopics.FAQ_TOPIC_WHAT_ARE_FRIENDS;
              Utils.launch(url);
            }
          });
    }
  }

  public void hookImageAction() {
    SWTSkinObject imageObject = skin.getSkinObject("buddies-viewer-nobuddies-graphic");
    if (null != imageObject) {
      SWTSkinButtonUtility imageButton = new SWTSkinButtonUtility(imageObject);
      imageButton.addSelectionListener(
          new ButtonListenerAdapter() {
            public void pressed(
                SWTSkinButtonUtility buttonUtility, SWTSkinObject skinObject, int stateMask) {
              FriendsToolbar friendsToolbar =
                  (FriendsToolbar) SkinViewManager.getByClass(FriendsToolbar.class);
              if (friendsToolbar != null) {
                friendsToolbar.addBuddy();
              }
            }
          });
    }
  }

  public boolean isEnabled() {
    return isEnabled;
  }

  public void setEnabled(boolean isEnabled) {
    if (this.isEnabled != isEnabled) {
      this.isEnabled = isEnabled;
      avatarsPanel.setEnabled(isEnabled);
      avatarsPanel.layout(true);
    }
  }

  public Chat getChat() {
    return chat;
  }

  /**
   * @return
   * @since 3.1.1.1
   */
  public Color getColorFileDragBorder() {
    return colorFileDragBorder;
  }

  /**
   * @return
   * @since 3.1.1.1
   */
  public Color getColorFileDragBG() {
    return colorFileDragBG;
  }
}