/*
 * Copyright 2000-2010 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.eclipse.agent;

import java.io.File;
import java.util.Stack;

import jetbrains.buildServer.agent.BuildProgressLogger;
import jetbrains.buildServer.agent.runner.ProcessListener;

import org.jetbrains.annotations.NotNull;

public class BuildLogger implements ProcessListener {

  private BuildProgressLogger myDelegate;

  private Stack<String> myTargets = new Stack<String>();

  BuildLogger(final @NotNull BuildProgressLogger delegate) {
    myDelegate = delegate;
  }

  public void onErrorOutput(final @NotNull String stderr) {
    myDelegate.error(stderr);
  }

  public void onStandardOutput(final @NotNull String stdout) {
    if (isTarget(stdout)) {
      final String target = getTarget(stdout);
      if (target.length() > 0) {
        if (!myTargets.isEmpty()) {
          final String finishedTask = myTargets.pop();
          myDelegate.targetFinished(finishedTask);
        }
        myTargets.push(target);
        myDelegate.targetStarted(target);
      }

    } else if (stdout.trim().length() > 0) {
      myDelegate.message(stdout);
    }
  }
  
  protected boolean isTarget(final @NotNull String line){
    return !line.startsWith(" ") && line.trim().endsWith(":");
  }
  
  protected String getTarget(final @NotNull String line){
    String target = line.trim();
    target = target.substring(0, target.length() -1);
    return target;
  }

  public void processFinished(int arg0) {
    // TODO Auto-generated method stub
  }

  public void processStarted(String arg0, File arg1) {
    // TODO Auto-generated method stub
  }

}
