/*
 * 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.builder;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import jetbrains.buildServer.RunBuildException;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.runner.ProgramCommandLine;
import jetbrains.buildServer.eclipse.java.BuildDescriptor;
import jetbrains.buildServer.eclipse.java.PlatformDescriptor;
import jetbrains.buildServer.util.FileUtil;

import org.apache.log4j.Logger;

public class SiteProjectBuilder extends FeatureBasedProjectBuilder {

  private final static Logger LOG = Logger.getLogger(SiteProjectBuilder.class);

  public SiteProjectBuilder(BuildRunnerContext buildRunnerContext, PlatformDescriptor platform, BuildDescriptor buildDescriptor) {
    super(buildRunnerContext, platform, buildDescriptor);
  }

  @Override
  public void init() throws RunBuildException {
    final File siteFolder = getBuildDescriptor().getProjectFile().getParentFile();
    final File siteFile = new File(siteFolder, "site.xml");
    getCommandLineSystemProperties().put("p2.category.site", String.format("file:%s", siteFile.getAbsolutePath()));
    super.init();
  }

  @Override
  public ProgramCommandLine[] makeCommandLines() {
    final String[] features = getBuildDescriptor().getTypeId();
    if (features.length == 1) {
      return super.makeCommandLines();
    }
    //several features found
    final LinkedList<ProgramCommandLine> out = new LinkedList<ProgramCommandLine>();
    for (String featureId : getBuildDescriptor().getTypeId()) {
      LOG.debug(String.format("Building feature '%s'", featureId));
      final ProgramCommandLine featureCommandLine = makeCommandLinesFor(getBuildDescriptor().getType(), featureId);
      out.add(featureCommandLine);
    }
    return out.toArray(new ProgramCommandLine[out.size()]);
  }

  @Override
  public void destroy() {
    try {
      //copy site.xml to output folder and setup qualifier
      final File siteFolder = getBuildDescriptor().getProjectFile().getParentFile();
      final File siteFile = new File(siteFolder, "site.xml");
      if (siteFile.exists()) {
        //.qualifier
        final List<String> siteContent = FileUtil.readFile(siteFile);
        final File siteCopy = new File(getOutputFolder(), "site.xml");
        final BufferedWriter out = new BufferedWriter(new FileWriter(siteCopy));
        final String actualQualifier = "." + getQualifier();
        for (String line : siteContent) {
          if (line.contains(".qualifier")) {
            String processedLine = line.replace(".qualifier", actualQualifier);
            LOG.debug(String.format("'%s' replaced with '%s'", line, processedLine));
            out.write(processedLine);
            out.write("\n");
          } else {
            out.write(line);
            out.write("\n");
          }
        }
        out.flush();
        out.close();
        LOG.debug(String.format("Site file '%s' populated to '%s'", siteFile, siteCopy));
      } else {
        LOG.warn(String.format("Site file '%s' does not exist", siteFile));
      }
    } catch (IOException e) {
      LOG.error(e.getMessage(), e);
    }
    super.destroy();
  }

}
