//
// 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 "flockImageScalerImpl.h"
#include "nsStringAPI.h"
#include "nsIProcess.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "nsComponentManagerUtils.h"

#if defined(XP_WIN)
# include <direct.h>
# include <process.h>
#else
# include <unistd.h>
#endif

NS_IMPL_ISUPPORTS1(flockImageScalerImpl, flockIImageScaler)

flockImageScalerImpl::flockImageScalerImpl()
{
  /* member initializers and constructor code */
}

flockImageScalerImpl::~flockImageScalerImpl()
{
  /* destructor code */
}

NS_IMETHODIMP flockImageScalerImpl::DoMagick(const char **aParams,
                                             PRUint32 aCount,
                                             PRBool *_retval)
{
  nsresult rv;
  nsCOMPtr<nsIProcess> proc(do_CreateInstance("@mozilla.org/process/util;1", &rv));
  NS_ENSURE_SUCCESS(rv, rv);

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

  nsCAutoString nativePath;
  nsCAutoString tmpDirNativePath;
    
  gmExec->GetNativePath(nativePath);
  flockImageTmpDir->GetNativePath(tmpDirNativePath);

#if defined(XP_WIN)
  _chdir(tmpDirNativePath.get());
  gmExec->Append(NS_LITERAL_STRING("gm.exe"));
#else
  chdir(tmpDirNativePath.get());
  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, aParams, aCount, &pid);
  NS_ENSURE_SUCCESS(rv, rv);

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

  *_retval = (exitCode == 0);

  return NS_OK;
}
