package util;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import conf.ConfigConstants;
import language.LanguageConstants;

/**
 *  Der Login-Dialog zur Einstellung des Hosts und User-Accounts für die
 *  Oracle-Datenbank.
 *
 * @author     T
 * @created    18. Juni 2001
 */
public class LoginDialog extends JDialog implements ActionListener, ItemListener
{
   
   KeyAdapter keyAdapter =
   new KeyAdapter()
   {
      public void keyPressed( KeyEvent e )
      {
         if ( e.getKeyCode() == KeyEvent.VK_ENTER )
         {
            ok();
         } else if ( e.getKeyCode() == KeyEvent.VK_ESCAPE )
         {
            cancel();
         }
      }
   };
   private static ConfigConstants cc = ConfigConstants.getInstance();
   private JComboBox connectBox;
   private JTextField hostField;
   private JTextField sidField;
   private JTextField userField;
   private JPasswordField passwordField;
   //  private JCheckBox passive;
   private String host;
   private String sid;
   private String user;
   private String password;
   private boolean isOK;
   private JButton ok;
   private JButton cancel;
   private String[] users;
   private String[] passes;
   private String[] hosts;
   private String[] sids;
   private String[] connects;
   
   private String sLogoFile = "data/bingo.jpg";
   
   private static LanguageConstants lc = LanguageConstants.getInstance();
   
   
   /**
    *  Konstruktor für das LoginDialog Objekt
    */
   public LoginDialog()
   {
      super( new JFrame(), lc.get( "loginTitle" ), true );
      setSize( 280, 380 );
      
      String s = System.getProperty( "file.separator" );
      sLogoFile = System.getProperty( "user.dir" ) + s + "data" + s + "bingo.jpg";
      //System.out.println(sLogoFile);
      Container content = this.getContentPane();
      
      content.setLayout( new BorderLayout() );
       
      Container cont = new Container();
      
      cont.setLayout( new GridLayout( 2, 1, 5, 5 ) );

      URL url = null;
      try
      {
        url = new URL("file", null, 0, sLogoFile);
      }
      catch (Exception e)
      {e.printStackTrace();}
      
      //JPanel panel = new ImagePanel( this.getClass().getClassLoader().getResource( sLogoFile ), new Dimension( 280, 80 ) );
      JPanel panel = new ImagePanel( url, new Dimension( 280, 80 ) );
      cont.add( panel );
      panel = createFieldPanel();
      cont.add( panel );
      
      panel = new JPanel();
      panel.setBorder( new EmptyBorder( 6, 0, 6, 12 ) );
      
      ok = new JButton( lc.get( "ok" ) );
      ok.addActionListener( this );
      ok.addKeyListener( keyAdapter );
      panel.add( ok );
      cancel = new JButton( lc.get( "cancel" ) );
      cancel.addActionListener( this );
      panel.add( cancel );
      
      content.add( cont, BorderLayout.CENTER );
      content.add( panel, BorderLayout.SOUTH );
    
      show();
      userField.selectAll();
   }
   
   
   /**
    *  Liefert das isOk-Attribut.
    *
    * @return    Das isOK-Attribut.
    */
   public boolean isOK()
   {
      return isOK;
   }
   
   
   /**
    *  Liefert die Host-Eingabe oder null, falls Abbruch gewählt wurde.
    *
    * @return    Der Host.
    */
   public String getHost()
   {
      return host;
   }
   
   
   /**
    *  Liefert den Service Name.
    *
    * @return    Der Service Name.
    */
   public String getSID()
   {
      return sid;
   }
   
   
   /**
    *  Liefert die User-Eingabe.
    *
    * @return    Der User.
    */
   public String getUser()
   {
      return user;
   }
   
   
   /**
    *  Liefert die Passwort-Eingabe.
    *
    * @return    Das Passwort.
    */
   public String getPassword()
   {
      return password;
   }
   
   
   /**
    *  Ok-Aktion.
    */
   public void ok()
   {
      
      if ( connectBox.getSelectedIndex() == connectBox.getItemCount() - 1 && userField.getText().length() == 0 && passwordField.getPassword().length == 0 )
      {
         user = null;
         password = null;
         sid = null;
         host = null;
         isOK = false;
         dispose();
      } else if ( hostField.hasFocus() && userField.getText().length() == 0 )
      {
         userField.requestFocus();
         isOK = false;
      /*
          } else if ( userField.hasFocus() && passwordField.getPassword().length == 0 ) {
          passwordField.requestFocus();
          isOK = false;
       */
      } else if ( passwordField.getPassword().length == 0 )
      {
         passwordField.requestFocus();
         JOptionPane.showMessageDialog( this, lc.get( "lDPasswordMsg" ), lc.get( "lDPasswordTitle" ),
         JOptionPane.INFORMATION_MESSAGE );
         isOK = false;
      } else
      {
         user = userField.getText();
         password = String.valueOf(passwordField.getPassword());
         host = hostField.getText();
         sid = sidField.getText();
         
         if ( Boolean.valueOf( cc.get( "firstStart" ) ).booleanValue() )
         {
            saveAccount( user, " ", host, sid );
            cc.set( "firstStart", "false" );
            cc.saveConfig();
         }
         
         isOK = true;
         dispose();
      }
   }
   
   
   /**
    *  Abbruch-Aktion.
    */
   public void cancel()
   {
      isOK = false;
      dispose();
   }
   
   
   /**
    *  Überwacht die Buttons.
    *
    * @param  evt  Das Event.
    */
   public void actionPerformed( ActionEvent evt )
   {
      Object source = evt.getSource();
      
      if ( source == ok )
      {
         ok();
      } else if ( source == cancel )
      {
         cancel();
      }
   }
   
   
   /**
    *  Überwacht das Textfeld.
    *
    * @param  evt  Das Event.
    */
   public void itemStateChanged( ItemEvent evt )
   {
      sidField.setText( sids[connectBox.getSelectedIndex()] );
      passwordField.setText( passes[connectBox.getSelectedIndex()] );
      userField.setText( users[connectBox.getSelectedIndex()] );
      hostField.setText( hosts[connectBox.getSelectedIndex()] );
   }
   
   
   // erstellt Eingabefelder
   private JPanel createFieldPanel()
   {
      Vector accounts = readAccounts();
      
      users = new String[accounts.size()];
      passes = new String[accounts.size()];
      hosts = new String[accounts.size()];
      sids = new String[accounts.size()];
      connects = new String[accounts.size()];
      
      int i = 0;
      
      for ( Enumeration enum = accounts.elements(); enum.hasMoreElements(); i++ )
      {
         Account ac = (Account) enum.nextElement();
         
         users[i] = ac.user;
         passes[i] = ac.pass;
         hosts[i] = ac.host;
         sids[i] = ac.nsid;
         if ( i < accounts.size() - 1 )
         {
            connects[i] = users[i] + "@" + sids[i];
         } else
         {
            connects[i] = "<" + lc.get( "noDB" ) + ">";
         }
      }
      
      JPanel container = new JPanel( new BorderLayout() );
      
      GridLayout layout = new GridLayout( 4, 2, 10, 10 );
      JPanel panel = new JPanel( layout );
      
      connectBox = new JComboBox( connects );
      connectBox.addKeyListener( keyAdapter );
      connectBox.addItemListener( this );
      
      
      JLabel label = new JLabel( "     " + lc.get( "user" ), SwingConstants.LEFT );
      
      panel.add( label );
      
      userField = new JTextField( "", 30 );
      userField.addKeyListener( keyAdapter );
      panel.add( userField );
      
      label = new JLabel( "     " + lc.get( "password" ), SwingConstants.LEFT );
      panel.add( label );
      
      passwordField = new JPasswordField( "", 30 );
      passwordField.addKeyListener( keyAdapter );
      panel.add( passwordField );
      
      label = new JLabel( "     " + lc.get( "host" ), SwingConstants.LEFT );
      panel.add( label );
      
      hostField = new JTextField( "", 30 );
      hostField.addKeyListener( keyAdapter );
      panel.add( hostField );
      
      label = new JLabel( "     " + lc.get( "service" ), SwingConstants.LEFT );
      panel.add( label );
      
      sidField = new JTextField( "", 30 );
      sidField.addKeyListener( keyAdapter );
      panel.add( sidField );
      
      hostField.setText( hosts[connectBox.getSelectedIndex()] );
      sidField.setText( sids[connectBox.getSelectedIndex()] );
      passwordField.setText( passes[connectBox.getSelectedIndex()] );
      userField.setText( users[connectBox.getSelectedIndex()] );
      
      container.add( connectBox, BorderLayout.NORTH );
      container.add( panel, BorderLayout.SOUTH );
      return container;
   }
   
   
   public Vector readAccounts()
   {
      
      URL u = this.getClass().getClassLoader().getResource( "data/accounts.dat" );
      Vector result = new Vector();
      
      try
      {
         BufferedReader bf = new BufferedReader( new InputStreamReader( u.openStream() ) );
         String line = bf.readLine();
         
         while ( line != null )
         {
            Account ac = new Account();
            StringTokenizer st = new StringTokenizer( line, ";" );
            
            ac.user = ( st.hasMoreTokens() ? st.nextToken() : "" ).trim();
            ac.pass = ( st.hasMoreTokens() ? st.nextToken() : "" ).trim();
            ac.host = ( st.hasMoreTokens() ? st.nextToken() : "-" ).trim();
            ac.nsid = ( st.hasMoreTokens() ? st.nextToken() : "-" ).trim();
            result.add( ac );
            line = bf.readLine();
         }
         bf.close();
      }
      catch ( Exception e )
      {
         SessionBuffer.log(e);
      }
      
      Account ac = new Account();
      
      ac.user = "";
      ac.pass = "";
      ac.host = "";
      ac.nsid = "";
      result.add( ac );
      
      return result;
   }
   
   
   private void saveAccount( String user, String pwd, String host, String service )
   {
      String s = System.getProperty( "file.separator" );
      String file = System.getProperty( "user.dir" ) + s + "data" + s + "accounts.dat";
      StringBuffer buf = new StringBuffer( user + ";" + pwd + ";" + host + ";" + service );
      
      try
      {
         FileWriter writer = new FileWriter( file );
         
         writer.write( buf.toString() );
         writer.flush();
      }
      catch ( Exception e )
      {
         SessionBuffer.log(e);
      }
   }
}
