package org.simtk.isimsu;

import java.net.*;
import java.io.*;

import javax.jnlp.BasicService;
import javax.jnlp.FileContents;
import javax.jnlp.PersistenceService;
import javax.jnlp.ServiceManager;

import javax.jnlp.UnavailableServiceException;

public class MuffinWrapper {
	
	PersistenceService persistentService; 
    BasicService basicService; 
    LogDialog logDialog;
    
	// constructor
	
	MuffinWrapper( LogDialog inputLogDialog ){
		persistentService = null;
		basicService      = null;
		logDialog         = inputLogDialog;
	}
	
	// get basic service
	
    public void showServices(){
		
       String[] availableServices = ServiceManager.getServiceNames();
       if( availableServices != null ){
	      logDialog.append( "Available services: " + availableServices.length + "\n" );
	      for( int ii = 0; ii < availableServices.length; ii++ ){
	         logDialog.append( " " + availableServices[ii] );
	      } 
	      logDialog.append( "\n\n" );
       } else {
    	   logDialog.append( "No jnlp services available.\n" );
       }
        return;
	}
	
	// get basic service
	
    public BasicService getBasicService(){
		
		// get basicSerivce if not set
		
		if( basicService == null ){
			
	       try {
	          basicService = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService"); 
	       } catch (UnavailableServiceException e) { 
	          basicService = null;
	          showServices();
	       }
	    } 
        return basicService;
	}

    // get persistent service
    
    public PersistenceService getPersistentService(){ 
    	
	   if( persistentService == null ){  
	      try { 
	    	  persistentService = (PersistenceService)ServiceManager.lookup("javax.jnlp.PersistenceService"); 
	       } catch (UnavailableServiceException exception ) { 
	    	   logDialog.append( "getPersistentService problem: " + exception.getMessage() );
	    	   showServices();
	       }
	    }
	   
	    return persistentService;

	}
    
    // given URL, get contents of associated muffin

	String getMuffinContents( URL url ){
			    
	    String methodName   =  "getMuffinContents:";  
	    logDialog.append( methodName + " begin\n" );
	    
	    PersistenceService persistentService = getPersistentService(); 
	    if( persistentService != null ){

	       // read in the contents of muffin
	    	
	       try {
	          FileContents fc = persistentService.get( url ); 
	          InputStream is  = fc.getInputStream(); 
	          int character; 
             StringBuffer stringBuffer = new StringBuffer();
	          while( (character = is.read()) > 0 ){ 
	             stringBuffer.append( (char) character );
	          } 
	          is.close();
	          return stringBuffer.toString();
	       } catch( java.net.MalformedURLException exception ){
	    	   logDialog.append( methodName + " invalid URL <" + url + "> " + exception.getMessage() + "\n" );
	       } catch( java.io.FileNotFoundException exception ){
	    	   logDialog.append( methodName + " URL <" + url + "> mot found: " + exception.getMessage() + "\n" );
	       } catch( java.io.IOException exception ){
	    	   logDialog.append( methodName + " IO problem reading URL <" + url + "> " + exception.getMessage() + "\n" );
	       }
           
	    } else {
	    	logDialog.append( methodName + " persistent service unavailable." + "\n" );
	    }
	    
	    return null;
    }
	
	// write muffin
	// return true if muffin successfully written; else false
	
    boolean writeMuffinContents( URL url, String muffinContents ){
    
	    PersistenceService persistentService = getPersistentService(); 
	    String methodName                    =  new String( "writeMuffinContents:" );
	    
	    if( persistentService != null ){

	       // write the string to a muffin
	    	
	       try {

	    	   long maxsize = muffinContents.length() > 4096 ? muffinContents.length() : 4096;
	    	   persistentService.create( url, maxsize); 
               FileContents fc = persistentService.get( url ); 
	      
	           OutputStream os = fc.getOutputStream(false); 
	           os.write( muffinContents.getBytes() ); 
	           os.close(); 
	    	   logDialog.append( methodName + " wrote muffin=<" + muffinContents + ">\n" );

	         return true;

	       } catch( Exception exception ){
	    	   logDialog.append( methodName + " IO problem writing muffin for URL <" +
                              url + "> " + exception.getMessage() + "\n" );
	       }
           return false;
	    } else {
	    	logDialog.append( methodName + " persistent service unavailable." + "\n" );
	    }
	    
	    return false;
    }

    // return array of all available muffins

	String[] findAllMuffins( URL url ){
		
		PersistenceService persistentService = getPersistentService(); 
		String methodName                    =  new String( "findAllMuffins:" );
		    
		if( persistentService != null ){
			
			try {

		      // read in the contents of a muffin
		      String [] muffins = persistentService.getNames(url);
		      return muffins;

			} catch( Exception exception ){
				logDialog.append( methodName + " Problem getting all muffins for URL <" + 
						          url + "> " + exception.getMessage() + "\n" );
			}
		 } else {
		    logDialog.append( methodName + " persistent service unavailable.\n" );
		    return null;
		 } 

		return null;
	}

}
