/*
 * RemoteFileSystemContext.java
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */
package org.rstudio.studio.client.workbench.model;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.resources.client.ImageResource;
import com.google.inject.Inject;
import org.rstudio.core.client.MessageDisplay;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.files.PosixFileSystemContext;
import org.rstudio.core.client.widget.ProgressIndicator;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.filetypes.FileTypeRegistry;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.views.files.model.DirectoryListing;
import org.rstudio.studio.client.workbench.views.files.model.FilesServerOperations;

import java.util.ArrayList;

public class RemoteFileSystemContext extends PosixFileSystemContext
{
   @Inject
   public RemoteFileSystemContext(FilesServerOperations server,
                                  FileTypeRegistry fileTypeRegistry,
                                  GlobalDisplay globalDisplay)
   {
      super();
      server_ = server;
      fileTypeRegistry_ = fileTypeRegistry;
      globalDisplay_ = globalDisplay;
   }

   public MessageDisplay messageDisplay()
   {
      return globalDisplay_;
   }

   public void cd(String relativeOrAbsolutePath)
   {
      final String newPath = combine(workingDir_, relativeOrAbsolutePath);

      final FileSystemItem newPathEntry = FileSystemItem.createDir(newPath);
      
      final ArrayList<FileSystemItem> fsi = new ArrayList<FileSystemItem>();

      server_.listFiles(
            newPathEntry,
            false, // since this is used for the file dialog don't 
                   // cause the call to reset the server monitoring state
            new ServerRequestCallback<DirectoryListing>()
            {
               @Override
               public void onError(ServerError error)
               {
                  if (callbacks_ != null)
                     callbacks_.onError(error.getUserMessage());
               }

               @Override
               public void onResponseReceived(final DirectoryListing response)
               { 
                  final JsArray<FileSystemItem> files = response.getFiles();
                  for (int i = 0; i < files.length(); i++)
                     fsi.add(files.get(i));
                  
                  workingDir_ = newPath;
                  contents_ = fsi.toArray(new FileSystemItem[0]);
                  
                  if (callbacks_ != null)
                     callbacks_.onNavigated();
               }
            });
   }

   public void refresh()
   {
      cd(workingDir_);
   }

   public void mkdir(final String directoryName, final ProgressIndicator progress)
   {
      String error;
      if (null != (error = validatePathElement(directoryName, true)))
      {
         progress.onError(error);
         return;
      }

      final String baseDir = workingDir_;
      String newPath = combine(baseDir, directoryName);
      final FileSystemItem newFolder = FileSystemItem.createDir(newPath);
      server_.createFolder(
            newFolder,
            new ServerRequestCallback<org.rstudio.studio.client.server.Void>()
            {
               @Override
               public void onError(ServerError error)
               {
                  progress.onError(error.getUserMessage());
               }

               @Override
               public void onResponseReceived(Void response)
               {
                  if (baseDir.equals(workingDir_))
                  {
                     progress.onCompleted();
                     if (callbacks_ != null)
                        callbacks_.onDirectoryCreated(newFolder);
                  }
               }
            });
   }

   public ImageResource getIcon(FileSystemItem item)
   {
      return fileTypeRegistry_.getIconForFile(item);
   }

   private final FilesServerOperations server_;
   private final FileTypeRegistry fileTypeRegistry_;
   private final GlobalDisplay globalDisplay_;
}

@@ -1740,18 +1740,69 @@
 lDisplay
+,%0A                                  Session session
 )%0A
-
    %7B%0A   
@@ -1919,16 +1919,42 @@
 isplay;%0A
+      session_ = session;%0A
    %7D%0A%0A  
@@ -2083,24 +2083,761 @@
 ePath)%0A   %7B%0A
+      // form the fallback path%0A      String fallbackPath;%0A      FileSystemItem projectDir = %0A            session_.getSessionInfo().getActiveProjectDir();%0A      if (projectDir == null)%0A         fallbackPath = session_.getSessionInfo().getDefaultWorkingDir();%0A      else%0A         fallbackPath = projectDir.getPath();%0A      %0A      cd(relativeOrAbsolutePath, fallbackPath);%0A   %7D%0A%0A   /**%0A    * Moves into the given directory (relative or absolute) and lists%0A    * the files in that directory.%0A    * %0A    * @param relativeOrAbsolutePath Path to attempt to enter%0A    * @param fallbackPath Fallback path to attempt if first path cannot be%0A    *    entered%0A    */%0A   public void cd(String relativeOrAbsolutePath, final String fallbackPath)%0A   %7B%0A
       final 
@@ -3436,32 +3436,215 @@
              if 
+(fallbackPath != null)%0A                  %7B%0A                     // try fallback if supplied%0A                     cd(fallbackPath, null);%0A                  %7D%0A                  else if 
 (callbacks_ != n
@@ -4297,33 +4297,36 @@
        %7D);%0A   %7D%0A
+   
 %0A
-
    public void r
@@ -5711,16 +5711,16 @@
 istry_;%0A
-
    priva
@@ -5758,10 +5758,45 @@
 splay_;%0A
+   private final Session session_;%0A
 %7D%0A

add resiliency to file dialog navigation (can't save when no R/ in pkg)