/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2006, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.soa.bpel.runtime.ws;

import org.jboss.soa.bpel.runtime.integration.ServerConfig;

import java.io.*;

class DeploymentBuilder
{
  private File war;
  private File webInf;
  private File wsdlDir;
  private DeploymentBuilder instance;

  private ServerConfig serverConfig;

  public DeploymentBuilder(ServerConfig serverConfig)
  {
    this.serverConfig = serverConfig;
  }

  public DeploymentBuilder setEndpoint(String endpointId)
  {
    File tmpDir = new File(serverConfig.getServerTempDir(), "riftsaw");

    tmpDir.mkdir();
    File fakeWebApp = new File(tmpDir, "riftsaw-"+endpointId+".war");
    File fakeWebInf = new File(fakeWebApp, "WEB-INF");
    fakeWebInf.mkdirs();

    // Workaround
    // See https://jira.jboss.org/jira/browse/JBWS-2718
    File fakeWSDLDir = new File(fakeWebInf, "wsdl");
    fakeWSDLDir.mkdirs();

    this.war = fakeWebApp;
    this.webInf = fakeWebInf;
    this.wsdlDir = fakeWSDLDir;

    return this;
  }

  public DeploymentBuilder setWSDL(File wsdl)
  {
    copy(wsdl, new File(this.wsdlDir, wsdl.getName()));

    // any related artifact as well (brute force, I know)
    File parent = wsdl.getParentFile();
    assert parent.isDirectory();

    FileFilter filter = new FileFilter()
    {
      public boolean accept(File f)
      {
        return (
            f.getName().endsWith(".wsdl")
                || f.getName().endsWith(".xsd")
                || f.isDirectory()
        );
      }
    };

    for(File f : parent.listFiles(filter))
    {
      if(f.equals(wsdl)) continue;
      copy(f, new File(this.wsdlDir, f.getName()));
    }
    return this;
  }

  public File build()
  {
    return this.war;
  }

  public static synchronized void copy(File src, File dest)
  {
    InputStream in = null;
    OutputStream out = null;

    try
    {
      if (src.isDirectory())
      {
        if (!dest.exists()) {
          dest.mkdir();
        }

        String[] children = src.list();
        for (int i=0; i<children.length; i++) {
          copy(new File(src, children[i]),
              new File(dest, children[i]));
        }
      } else {

        in = new FileInputStream(src);
        out = new FileOutputStream(dest);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
          out.write(buf, 0, len);
        }
        in.close();
        out.close();
      }

    }
    catch (IOException e)
    {
      throw new RuntimeException("Failed to copy files", e);
    }
    finally
    {
      try
      {
        if(in!=null) in.close();
      }
      catch (IOException e)
      {
        //
      }

      try
      {
        if(out!=null) out.close();
      }
      catch (IOException e)
      {
        //
      }
    }
  }
}
