/*
 * Copyright 2000-2013 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 jetbrains.buildServer.buildTriggers.url;

import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.buildTriggers.BuildTriggerException;
import jetbrains.buildServer.buildTriggers.PolledTriggerContext;
import jetbrains.buildServer.buildTriggers.async.BaseAsyncPolledBuildTrigger;
import jetbrains.buildServer.serverSide.TeamCityProperties;
import jetbrains.buildServer.serverSide.impl.SecondaryNodeSecurityManager;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Map;

import static jetbrains.buildServer.buildTriggers.url.UrlBuildTriggerUtil.*;

/**
 * @author vbedrosova
 */
public class UrlAsyncBuildTrigger extends BaseAsyncPolledBuildTrigger {
  @NotNull
  private static final Logger LOG = LoggerFactory.getLogger(UrlAsyncBuildTrigger.class);

  @NotNull
  private final ResourceHashProviderFactory resourceHashProviderFactory;

  public UrlAsyncBuildTrigger(@NotNull final ResourceHashProviderFactory resourceHashProviderFactory) {
    this.resourceHashProviderFactory = resourceHashProviderFactory;
  }

  @Nullable
  @Override
  public String triggerBuild(@Nullable String oldHash, @NotNull PolledTriggerContext context) throws BuildTriggerException {
    final Map<String, String> props = context.getTriggerDescriptor().getProperties();

    final String urlStr = props.get(URL_PARAM);

    if (StringUtil.isEmptyOrSpaces(urlStr)) {
      throw new BuildTriggerException(DISPLAY_NAME + " settings are invalid in the build configuration " + context.getBuildType() + ": no URL provided");
    }

    LOG.debug(DISPLAY_NAME + " checks if the resource specified by " + urlStr + " changed");

    try {
      final String newHash = SecondaryNodeSecurityManager.runSafeNetworkOperation(() -> resourceHashProviderFactory
        .createResourceHashProvider(urlStr)
        .getResourceHash(TriggerParameters.create(
          urlStr,
          props.get(USERNAME_PARAM),
          props.get(PASSWORD_PARAM),
          props.get(OAUTH_SERVER_URL), TeamCityProperties.getInteger(CONNECTION_TIMEOUT_PROP, DEFAULT_CONNECTION_TIMEOUT), oldHash
        )));

      if (oldHash == null) { // do not trigger build after adding trigger
        LOG.debug(DISPLAY_NAME + ": no previous data for the resource " + urlStr + ": null" + " -> " + newHash);
      } else if (newHash.equals(oldHash)) {
        LOG.debug(DISPLAY_NAME + ": the resource not changed " + urlStr + ": " + oldHash + " -> " + newHash);
      } else {
        LOG.info(DISPLAY_NAME + ": the resource changed " + urlStr + ": " + oldHash + " -> " + newHash);
        context.getBuildType().addToQueue(DISPLAY_NAME + " " + urlStr);
      }

      return newHash;

    } catch (Throwable e) {
      throw new BuildTriggerException(DISPLAY_NAME + " failed with error: " + e.getMessage(), e);
    }
  }

  @Override
  public int getPollInterval(@NotNull PolledTriggerContext context) {
    String pollInterval = context.getBuildType().getParameterValue("teamcity.internal.url.build.trigger.poll.interval");
    if (pollInterval != null) {
      return Integer.parseInt(pollInterval);
    }
    return TeamCityProperties.getInteger(POLL_INTERVAL_PROP, DEFAULT_POLL_INTERVAL);
  }
}
