/* vim: ts=4 sw=4 
*/
/*
 * BEGIN FLOCK GPL
 *
 * Copyright Flock Inc. 2005-2009
 * http://flock.com
 *
 * This file may be used under the terms of the
 * GNU General Public License Version 2 or later (the "GPL"),
 * http://www.gnu.org/licenses/gpl.html
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * END FLOCK GPL
 */


#include "flockAsyncImageScalerImpl.h"

#include "nsXPCOM.h"
#include "nsMemory.h"
#include "nsStringAPI.h"

#include "nsIProcess.h"

#include "nsDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "nsComponentManagerUtils.h"


NS_IMPL_THREADSAFE_ISUPPORTS1(flockAsyncImageScalerImpl,
                              flockIAsyncImageScalerInternal)

flockAsyncImageScalerImpl::flockAsyncImageScalerImpl()
  : mShuttingDown(PR_FALSE)
{
}

flockAsyncImageScalerImpl::~flockAsyncImageScalerImpl()
{
}

NS_IMETHODIMP flockAsyncImageScalerImpl::DoAsyncMagick(char **aParams,
                                                       PRUint32 aCount,
                                                       flockIAsyncImageScalerListener *aListener)
{
  if (mShuttingDown) {
    NS_WARNING("flockAsyncImageScalerImpl::DoAsyncMagick called while shutting down");
    return NS_ERROR_NOT_INITIALIZED;
  }

  class ParamCleanup {
  public:
    ParamCleanup(char **aParams, PRUint32 aCount)
      : mParams(aParams), mCount(aCount) { }

    ~ParamCleanup() {
      NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mCount, mParams);
    }

  private:
    char **mParams;
    PRUint32 mCount;
  };

  ParamCleanup cleanup(aParams, aCount);

  nsresult rv;
  nsCOMPtr<nsIProcess> proc(do_CreateInstance("@mozilla.org/process/util;1", &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIFile> gmExec;
  NS_GetSpecialDirectory(NS_OS_CURRENT_PROCESS_DIR, getter_AddRefs(gmExec));

#if defined(XP_WIN)
  gmExec->Append(NS_LITERAL_STRING("gm.exe"));
#else
  gmExec->Append(NS_LITERAL_STRING("gm"));
#endif

  PRBool gmExists = PR_FALSE;
  rv = gmExec->Exists(&gmExists);
  if (!gmExists) {
    return NS_ERROR_UNEXPECTED;
  }

  rv = proc->Init(gmExec);
  NS_ENSURE_SUCCESS(rv, rv);

  PRUint32 pid;
  rv = proc->Run(/*blocking*/PR_TRUE,
                 const_cast<const char **>(aParams), aCount,
                 &pid);
  NS_ENSURE_SUCCESS(rv, rv);

  PRInt32 exitCode;
  rv = proc->GetExitValue(&exitCode);
  NS_ENSURE_SUCCESS(rv, rv);

  return aListener->OnFinished((exitCode != 0));
}
