/*
 * Copyright 2000-2015 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.clouds.vmware;

import com.intellij.openapi.diagnostic.Logger;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;
import jetbrains.buildServer.clouds.CloudErrorInfo;
import jetbrains.buildServer.clouds.CloudErrorProvider;
import jetbrains.buildServer.util.ExceptionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Eugene Petrenko
 *         Created: 08.12.2009 9:48:26
 */
public class ErrorHolder implements CloudErrorProvider {
  private final Logger LOG = Logger.getInstance(ErrorHolder.class.getName());
  private final AtomicReference<CloudErrorInfo> myError = new AtomicReference<CloudErrorInfo>(null);
  private final ConcurrentMap<String, ErrorHolder> myNamedSubErrors = new ConcurrentHashMap<String, ErrorHolder>();

  protected Collection<? extends ErrorHolder> getChildErrors() {
    return Collections.emptyList();
  }

  @Nullable
  public final CloudErrorInfo getErrorInfo() {
    CloudErrorInfo error = myError.get();
    if (error != null) return error;
    for (ErrorHolder holder : getChildErrors()) {
      error = holder.getErrorInfo();
      if (error != null) return error;
    }
    for (ErrorHolder holder : myNamedSubErrors.values()) {
      error = holder.getErrorInfo();
      if (error != null) return error;
    }

    return null;
  }

  public final void setErrorInfo(@Nullable final CloudErrorInfo info) {
    myError.set(info);
  }

  @NotNull
  public ErrorHolder getNamedError(@NotNull final String name) {
    ErrorHolder eh = new ErrorHolder();
    final ErrorHolder old = myNamedSubErrors.putIfAbsent(name, eh);
    return old == null ? eh : old;
  }

  @NotNull
  public final Runnable wrapPermanentError(@NotNull final String operationName, @NotNull final Runnable r) {
    return getNamedError(operationName).wrap(operationName, r);
  }

  @NotNull
  public final Runnable wrapPermanentError(@NotNull final String operationName, @NotNull Collection<? extends ErrorHolder> multicast, @NotNull final Runnable r) {
    return getNamedError(operationName).wrap(operationName, multicast, r);
  }

  @NotNull
  public final Runnable wrap(@NotNull final String operationName, @NotNull final Runnable r) {
    return wrap(operationName, Collections.<ErrorHolder>emptyList(), r);
  }

  @NotNull
  public final Runnable wrap(@NotNull final String operationName, @NotNull final Collection<? extends ErrorHolder> muticast, @NotNull final Runnable r) {
    return ExceptionUtil.catchAll("VMWare plugin " + operationName, new Runnable() {
      public void run() {
        try {
          r.run();
          setErrorInfo(null);
        } catch (Throwable t) {
          LOG.warn("Operation failed. " + t.getMessage(), t);
          final CloudErrorInfo errorInfo = new CloudErrorInfo("Failed to " + operationName + ". " + t.getMessage(), "", t);

          setErrorInfo(errorInfo);
          for (ErrorHolder holder : muticast) {
            holder.setErrorInfo(errorInfo);
          }
        }
      }
    });
  }
}
