package oracle.forms.fd;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.StringTokenizer;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import oracle.forms.ui.VBean;
import oracle.forms.handler.IHandler;
import oracle.forms.properties.ID;

    /**
     * A javabean that read/display/write images
     * 
     * image can be read from file system or database BLOB column
     * image can be written to database BLOB column
     * 
     * use the JDBC driver to connect to the database
     * 
     * @author Francois Degrelle
     * @version 1.0
     *
     */

    public class HandleImage   extends VBean
    {
      public final static ID SETPOS          = ID.registerProperty("SETPOS");   
      public final static ID SETBG           = ID.registerProperty("SETBG");   
      public final static ID SETLOG          = ID.registerProperty("SETLOG");   
      public final static ID CLEAR           = ID.registerProperty("CLEAR");   
      public final static ID GETSIZE         = ID.registerProperty("GETSIZE");           
      public final static ID GETMODIFIER     = ID.registerProperty("GETMODIFIER");           
      public final static ID READIMGBASE     = ID.registerProperty("READIMGBASE");         
      public final static ID READIMGFILE     = ID.registerProperty("READIMGFILE");         
      public final static ID WRITEIMGBASE    = ID.registerProperty("WRITEIMGBASE");               
      public final static ID SETSCROLL       = ID.registerProperty("SETSCROLL");               
      protected static final ID SETCONN      = ID.registerProperty("SETCONN");
      protected static final ID SETUSER      = ID.registerProperty("SETUSER");    
      protected static final ID SETPWD       = ID.registerProperty("SETPWD");          
      protected static final ID SETTABLEINFO = ID.registerProperty("SETTABLEINFO");          
      private   IHandler    m_handler; 
      private   myPanel     mp = null ;
      private   JScrollPane jsp = null ;      
      private   Image       img = null ;
      private   boolean     bLog = false ;
      private   boolean     bImg = false ;
      private   URL         m_codeBase;
      private   File        file_image = null ;
      private   FileInputStream fis = null ;
      private   int         iMageSize = 0 ;
      private   JPanel      jp = new JPanel() ;
      private   Color       colorBackGround = Color.white ;
      private   Border      border, loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);      
     
      public HandleImage()
      {
         super();
      }
       
      public void init(IHandler handler)
      {
        m_handler = handler;
        super.init(handler);
        try
        {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          SwingUtilities.updateComponentTreeUI(this);
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
        }             
        // create the panel
        mp = new myPanel(this.getWidth(),this.getHeight()) ;
        //mp.setPreferredSize(new Dimension(this.getWidth(),this.getHeight()));
        mp.setVisible(true);
        border = BorderFactory.createTitledBorder(loweredetched) ;
        mp.setBorder(border);
        // create the JScrollPane and associate with the panel
        jsp =  new JScrollPane(mp) ;
        jsp.setPreferredSize(new Dimension(this.getWidth(),this.getHeight()));
        jsp.setVisible(true);
        jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        add(jsp);
      }     
 
      /*
       *  set the properties of the bean
       */
      public boolean setProperty(ID property, Object value)
      {
        // read an image from a file
        if (property == READIMGFILE)  
        {
          String sFileName = value.toString() ;
          img = loadImage( sFileName ) ;
          bImg = true ;
          mp.setImage(img) ;
          return true;
        }
        
        // read an image from the database
        else if (property == READIMGBASE)  
        {
          int iID = Integer.parseInt(value.toString()) ;
         
          try {
          img = LectureBlob.Lecture( iID ) ;
          bImg = true ;          
          }
          catch (Exception e) {
               System.out.println( "Exception in LectureBlob.Lecture() "+e.toString()) ;
          }          
          mp.setImage(img) ;
          return true;
        }
        
        // write an image to the database
        else if (property == WRITEIMGBASE)  
        {
          int iID = Integer.parseInt(value.toString()) ;
         
          try {
          System.out.println("Start Ecriture()") ;
          LectureBlob.Ecriture( iID, fis, iMageSize ) ;
          System.out.println("End Lecture()") ;
          }
          catch (Exception e) {
               System.out.println( e.toString()) ;
          }          
          return true;
        }        

        // init the connect string
        else if (property == SETCONN)
         {
            LectureBlob.sConn = (String)value ;
            log("InitConn="+LectureBlob.sConn) ;                 
            return true;
         }     

        // init the username
        else if (property == SETUSER)
         {
            LectureBlob.sUser = (String)value ;
            log("InitUser="+LectureBlob.sUser) ;       
            return true;
         }     

        // init the password
        else if (property == SETPWD)
         {
            LectureBlob.sPwd  = (String)value ;
            log("InitPwd="+LectureBlob.sPwd) ;       
            return true;
         }     

        // set the background color
        else if (property == SETTABLEINFO) 
        {
          String s = value.toString().trim();
          String sTable="", sCol="", sIdent="" ;
          StringTokenizer st = new StringTokenizer(s,",");
          LectureBlob.sTable  = st.nextToken() ;
          LectureBlob.sColumn = st.nextToken() ;
          LectureBlob.sLookup = st.nextToken() ;

          return true;
        }        
        
        // set the position of the image
        else if (property == SETPOS) 
        {
          int iPos = new Integer((String)value).intValue() ;
          return true;
        }
        
        // set the background color
        else if (property == SETBG) 
        {
          String color = value.toString().trim();
          int r=-1, g=-1, b=-1, c=0 ;
          StringTokenizer st = new StringTokenizer(color,",");
          while (st.hasMoreTokens()) {
                   c = new Integer((String)st.nextToken()).intValue()  ;
                   if( (c <0) || (c > 255) ) c = 0 ;
                   if( r == -1 ) r = c ;
                   else if( g == -1 ) g = c ;
                   else if( b == -1 ) b = c ;
                 }
          mp.setBGColor(new Color(r, g, b)) ;
          return true;
        }

        // clear the image
        else if (property == CLEAR) 
        {
          log("Clear imge") ;          
          img = null ;
          LectureBlob.blobImage = null ;
          //mp.revalidate() ;
          mp.setImage(null) ;
          return true;
        }

        // allow/unallow the scrollbar
        else if (property == SETSCROLL) 
        {
          String s = (String)value ;
          if( s.equalsIgnoreCase("TRUE"))
          {
            jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
            jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
          }
          else 
          {
            jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
            jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
          }            
          return true;
        }        
        
        // set the log flag to output the messages on the console
        else if (property == SETLOG) 
        {
          String s = (String)value ;
          if( s.equalsIgnoreCase("TRUE"))
          {
            bLog= true ;
            LectureBlob.bLog = true ;
            log("Lecture.bLog="+LectureBlob.bLog) ;
          }
          else 
          {
            bLog = false ;
            LectureBlob.bLog = false ;
          }            
          return true;
        }        
        
        else
        {
         return super.setProperty(property, value);
        }
      }

      /*
       * Get the properties from the bean
       */
      public Object getProperty(ID pId) // get the whole string
      {
        if( pId == GETSIZE)
        {
          return "" + mp.getImageWidth()+","+mp.getImageHeight() ;
        }
        
        else
        {
          return super.getProperty(pId);
        }
      }
     
     
    /*
     *  Load an image from JAR file, Client machine or Internet URL 
     */
    private Image loadImage(String p_imageName)
    {
      URL imageURL = null;
      boolean loadSuccess = false;
      Image img = null ;
      String imageName = p_imageName ;
      
      try {
      file_image = new File( imageName );
      fis = new FileInputStream( file_image );
      }
      catch( Exception e )
          {
            e.printStackTrace();
          }      
      iMageSize = ( int )file_image.length() ;
      imageName = "file:///" + p_imageName ;
      //JAR
      log("Searching JAR for " + imageName);
      imageURL = getClass().getResource(imageName);
      if (imageURL != null)
      {
        log("URL: " + imageURL.toString());
        try
        {
          img = Toolkit.getDefaultToolkit().getImage(imageURL);
          loadSuccess = true;
          log("Image found in JAR: " + imageURL.toString());
          return img ;
        }
        catch (Exception ilex)
        {
          log("Error loading image from JAR: " + ilex.toString());
        }
      }
      else
      {
        log("Unable to find " + imageName + " in JAR");
      }

      //DOCBASE
      if (loadSuccess == false)
      {
        log("Searching docbase for " + imageName);
        try
        {
          if (imageName.toLowerCase().startsWith("http://")||imageName.toLowerCase().startsWith("https://"))
          {
            imageURL = new URL(imageName);
          }
          else if(imageName.toLowerCase().startsWith("file:"))
          {
            imageURL = new URL(imageName);
          }
          else
          {
            imageURL = new URL(m_codeBase.getProtocol() + "://" + m_codeBase.getHost() + ":" + m_codeBase.getPort() + imageName);
          }
          log("Constructed URL: " + imageURL.toString());
          try
          {
            img = createImage((java.awt.image.ImageProducer) imageURL.getContent());
            loadSuccess = true;
            log("Image found in DOCBASE: " + imageURL.toString());
            return img ;
          }
          catch (Exception ilex)
          {
            log("Error reading image - " + ilex.toString());
          }
        }
        catch (java.net.MalformedURLException urlex)
        {
          log("Error creating URL - " + urlex.toString());
        }
      }

      //CODEBASE
      if (loadSuccess == false)
      {
        log("Searching codebase for " + imageName);
        try
        {
          imageURL = new URL(m_codeBase, imageName);
          log("Constructed URL: " + imageURL.toString());
          try
          {
            img = createImage((java.awt.image.ImageProducer) imageURL.getContent());
            loadSuccess = true;
            log("Image found in CODEBASE: " + imageURL.toString());
            return img ;
          }
          catch (Exception ilex)
          {
                  log("Error reading image - " + ilex.toString());
          }
        }
        catch (java.net.MalformedURLException urlex)
        {
          log("Error creating URL - " + urlex.toString());
        }
      }

      if (loadSuccess == false)
      {
        log("Error image " + imageName + " could not be located");
      }
      return img ;
    }
    
    
  public void log( String sMessage )
  {
    if( bLog) System.out.println( sMessage ) ;
  }    
  
}     