/*
** Apollo - Test Skeleton Toolkit for Web Start/JNLP
** Copyright (c) 2001, 2002, 2003 by Gerald Bauer
**
** This program is free software.
**
** You may redistribute it and/or modify it under the terms of the GNU
** General Public License as published by the Free Software Foundation.
** Version 2 of the license should be included with this distribution in
** the file LICENSE, as well as License.html. If the license is not
** included with this distribution, you may find a copy at the FSF web
** site at 'www.gnu.org' or 'www.fsf.org', or you may write to the
** Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/

package apollo.dev;

import java.io.*;
import java.net.*;
import java.util.*;
import apollo.*;
import houston.*;

public class DevPersistenceService implements PersistenceService
{
   static Logger T = Logger.getLogger( DevPersistenceService.class );

   File _muffinDir;

   public DevPersistenceService()
   {
      File userDir = new File( System.getProperty( "user.home" ) );
      File rootDir = new File( userDir, ".apollo" );
      _muffinDir = new File( rootDir, "muffins" );

      if( !_muffinDir.exists() )
         _muffinDir.mkdirs();
   }

   public void setTag( URL url, int tag )
          throws MalformedURLException
   {
      // fix: use a property file to set/get tag
   }

   public FileContents get( URL url )
          throws MalformedURLException, IOException, FileNotFoundException
   {
      return new DevFileContents( mapUrlToFile( url ) );
   }

   public String[] getNames( URL url )
          throws MalformedURLException, IOException
   {
      File file = mapUrlToFile( url );

      // if url doesn't end with slash; strip file name and use parent directory for lookup
      if( !url.toString().endsWith( "/" ) )
         file = file.getParentFile();

      File entries[] = file.listFiles();
      ArrayList tempNames = new ArrayList();

      if( entries != null )
      {
         for( int i = 0; i < entries.length; i++ )
         {
            File entry = entries[i];
            if( entry.isDirectory() )
               continue;
            else
               tempNames.add( entry.getName() );
         }
      }

      return ( String[] ) tempNames.toArray( new String[0] );
   }

   public int getTag( URL url )
          throws MalformedURLException
   {
      // fix: use a property file to set/get tag
      return CACHED;
   }

   public long create( URL url, long maxSize )
          throws MalformedURLException, IOException
   {
      File file = mapUrlToFile( url );
      file.getParentFile().mkdirs();
      file.createNewFile();
      return maxSize;
   }

   public void delete( URL url )
          throws MalformedURLException, IOException
   {
      File file = mapUrlToFile( url );
      file.delete();
   }

   private static String escapeSpecialCharacters( String line )
   {
      // resolve entities (aka escape sequences)
      // - known entities:
      //   : -> &c

      // how about space?

      StringBuffer buf = new StringBuffer();

      for( int pos = 0; pos < line.length();  )
      {
         char c = line.charAt( pos );

         switch ( c )
         {
            case ':':
               buf.append( "&c" );
               ++pos;
               break;
            default:
               buf.append( c );
               ++pos;
               break;
         }
      }
      return buf.toString();
   }

   private File mapUrlToFile( URL url )
   {
      String protocol = url.getProtocol();
      String host = url.getHost();
      int port = url.getPort();
      String path = url.getPath();

      // set default port to 80 if protocol is http
      if( port == -1
             && protocol.toLowerCase().equals( "http" ) )
      {
         port = 80;
      }

      if( host.equals( "" ) )
         host = "localhost";

      T.debug( "protcol=" + protocol );
      T.debug( "host=" + host );
      T.debug( "port=" + port );
      T.debug( "path=" + path );

      StringBuffer mangledPathBuf = new StringBuffer();
      mangledPathBuf.append( protocol
             + "/" + host
             + "/" + port );

      // remove leading slash e.g (/c:/test)
      //   /test/test.html

      if( path.startsWith( "/" ) )
         path = path.substring( 1 );

      T.debug( "path=" + path );

      StringTokenizer tok = new StringTokenizer( path, "/" );
      while( tok.hasMoreTokens() )
      {
         String name = tok.nextToken();
         name = escapeSpecialCharacters( name );

         mangledPathBuf.append( "/" + name );
      }

      T.debug( "mangledPath=" + mangledPathBuf.toString() );

      File mangledPathFile = new File( _muffinDir, mangledPathBuf.toString() );
      return mangledPathFile;
   }

}