/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.internal.statistic.updater;

import com.intellij.ide.AppLifecycleListener;
import com.intellij.internal.statistic.StatisticsUploadAssistant;
import com.intellij.internal.statistic.connect.StatisticsService;
import com.intellij.internal.statistic.connect.StatisticsServiceEP;
import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.NotificationsConfiguration;
import com.intellij.notification.impl.NotificationsConfigurationImpl;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Ref;
import com.intellij.util.Alarm;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;

public class SendStatisticsComponent implements ApplicationComponent {

  private static final Logger LOG = Logger.getInstance(SendStatisticsComponent.class);

  private static final int DELAY_IN_MIN = 10;

  private final Alarm myAlarm;

  public SendStatisticsComponent() {
    myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, ApplicationManager.getApplication());

    NotificationsConfigurationImpl.remove("SendUsagesStatistics");
    NotificationsConfiguration.getNotificationsConfiguration().register(
      StatisticsNotificationManager.GROUP_DISPLAY_ID,
      NotificationDisplayType.STICKY_BALLOON,
      false);
  }

  private void runStatisticsService() {
    final StatisticsService statisticsService = StatisticsUploadAssistant.getStatisticsService();

    if (StatisticsUploadAssistant.isShouldShowNotification()) {
      Application app = ApplicationManager.getApplication();
      app.getMessageBus().connect(app).subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener.Adapter() {
        @Override
        public void appFrameCreated(String[] commandLineArgs, @NotNull Ref<Boolean> willOpenProject) {
          myAlarm.addRequest(new Runnable() {
            @Override
            public void run() {
              StatisticsNotificationManager.showNotification(statisticsService);
            }
          }, 30 * 1000);
        }
      });
    }
    else if (StatisticsUploadAssistant.isSendAllowed() && StatisticsUploadAssistant.isTimeToSend()) {
      StatisticsService serviceToUse = null;
      StatisticsServiceEP[] extensions = StatisticsService.EP_NAME.getExtensions();
      if (extensions.length > 1) {
        LOG.warn(String.format("More than one stats service detected (%s). Falling back to the built-in one", Arrays.toString(extensions)));
      }
      else if (extensions.length == 1) {
        serviceToUse = extensions[0].getInstance();
      }
      if (serviceToUse == null) {
        serviceToUse = statisticsService;
      }
      runWithDelay(serviceToUse);
    }
  }

  private void runWithDelay(final @NotNull StatisticsService statisticsService) {
    myAlarm.addRequest(new Runnable() {
      @Override
      public void run() {
        statisticsService.send();
      }
    }, DELAY_IN_MIN * 60 * 1000);
  }

  @Override
  public void initComponent() {
    if (ApplicationManager.getApplication().isUnitTestMode()) return;

    runStatisticsService();
  }

  @Override
  public void disposeComponent() {
  }

  @NotNull
  @Override
  public String getComponentName() {
    return SendStatisticsComponent.class.getName();
  }
}

@@ -668,34 +668,75 @@
 lij.ide.
-AppLifecycleListen
+FrameStateListener;%0Aimport com.intellij.ide.FrameStateManag
 er;%0Aimpo
@@ -1124,61 +1124,8 @@
 pl;%0A
-import com.intellij.openapi.application.Application;%0A
 impo
@@ -1320,16 +1320,125 @@
 api.
-util.Ref
+wm.WindowManager;%0Aimport com.intellij.openapi.wm.ex.WindowManagerEx;%0Aimport com.intellij.openapi.wm.impl.IdeFrameImpl
 ;%0Aim
@@ -1782,38 +1782,138 @@
 %0A  p
-ublic SendStatisticsComponent(
+rivate final FrameStateManager myFrameStateManager;%0A%0A  public SendStatisticsComponent(@NotNull FrameStateManager frameStateManager
 ) %7B%0A
@@ -2261,16 +2261,62 @@
  false);
+%0A%0A    myFrameStateManager = frameStateManager;
 %0A  %7D%0A%0A  
@@ -2526,155 +2526,53 @@
     
-Application app = ApplicationManager.getApplication();%0A      app.getMessageBus().connect(app).subscribe(AppLifecycleListener.TOPIC, new AppLifecycl
+myFrameStateManager.addListener(new FrameStat
 eLis
@@ -2631,119 +2631,205 @@
 oid 
-app
+on
 Frame
-Created(String%5B%5D commandLineArgs, @NotNull Ref%3CBoolean%3E willOpenProject) %7B%0A          myAlarm.addRequest
+Activated() %7B%0A          if (((WindowManagerEx)WindowManager.getInstance()).getMostRecentFocusedWindow() instanceof IdeFrameImpl) %7B%0A            ApplicationManager.getApplication().invokeLater
 (new
@@ -2846,32 +2846,34 @@
 ) %7B%0A            
+  
 @Override%0A      
@@ -2870,32 +2870,34 @@
 ide%0A            
+ 
+ 
 public void run(
@@ -2892,32 +2892,34 @@
 ic void run() %7B%0A
+  
               St
@@ -2987,32 +2987,34 @@
 e);%0A            
+  
 %7D%0A          %7D, 3
@@ -3013,22 +3013,79 @@
     
-%7D, 30 * 1000);
+  %7D);%0A            myFrameStateManager.removeListener(this);%0A          %7D
 %0A   

Send statistics notification: use "onFrameActivated" event instead of "appFrameCreated" and ApplicationManager.getApplication().invokeLater instead of alarm with delay