package siprp.higiene.marcacoes;


import static com.evolute.utils.strings.UnicodeLatin1Map.eacute;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import siprp.data.outer.MarcacoesTecnicosHstData;
import siprp.higiene.HigieneDataProvider;

import com.evolute.entity.ProviderInterface;
import com.evolute.utils.Singleton;
import com.evolute.utils.tables.BaseTable;
import com.evolute.utils.tables.ColumnizedObjectArray;
import com.evolute.utils.tables.VectorTableModel;
import com.evolute.utils.ui.CustomJDialog;
import com.evolute.utils.ui.DialogException;
import com.evolute.utils.ui.button.BetterButtonGroup;
import com.evolute.utils.ui.text.CopyPasteHandler;

/**
 *
 * @author fpalma
 */
public class TecnicoEditor extends CustomJDialog
	implements ActionListener, ListSelectionListener
{

	private static final long serialVersionUID = 1L;
	
	private ProviderInterface JDO;
	private HigieneDataProvider provider;
	private BaseTable table;
	private VectorTableModel<ColumnizedObjectArray> model;
	private JButton okButton;
	private JButton cancelarButton;
	private JButton novoButton;
	private JTextField nomeText;
	private JTextField iniciaisText;
	private JCheckBox checkSuperior;
	private Integer id;
	private boolean isNew = false;
	private BetterButtonGroup corGroup;
	private JRadioButton cores[];
	
	/** Creates a new instance of MedicoEditor */
	public TecnicoEditor( JFrame owner )
		throws Exception
	{
		super( owner, true );
		provider = (HigieneDataProvider)HigieneDataProvider.getProvider();
		JDO = ( ProviderInterface ) Singleton.getInstance( Singleton.DEFAULT_JDO_PROVIDER );
		setupComponents();
	}
    
	private void setupComponents()
		throws Exception
	{
		setSize( 600, 300 );
		setResizable( false );
		setTitle( "Criar/Editar T\u00e9cnico" );
		centerSuper();
		
		model = new VectorTableModel<ColumnizedObjectArray>( new String[]{ "Nome", "Iniciais", "Cor", "Superior" } );
		table = new BaseTable( model );
		table.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
		table.setTableCellRenderer( new TecnicoRenderer() );
		JScrollPane scp = new JScrollPane();
		scp.setMinimumSize( new Dimension( 300, 200 ) );
		scp.setMaximumSize( new Dimension( 300, 200 ) );
		scp.setPreferredSize( new Dimension( 300, 200 ) );
		scp.setSize( new Dimension( 300, 200 ) );
		scp.setViewportView( table );
		scp.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		scp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
		table.fixColumnWidth( 0, 200 );
		table.setNonResizableNorReordable();
		table.getSelectionModel().addListSelectionListener( this );
		Object obj[][] = provider.getAllTecnicosHST();
		Vector<ColumnizedObjectArray> tecnicosHST = new Vector<ColumnizedObjectArray>();
		for( int n = 0; n < obj.length; n++ )
		{
			tecnicosHST.add( new ColumnizedObjectArray( obj[ n ], true ) );
		}
		model.setValues( tecnicosHST );
		
		okButton = new JButton( "OK" );
		cancelarButton = new JButton( "Cancelar" );
		novoButton = new JButton( "Novo" );
		okButton.addActionListener( this );
		cancelarButton.addActionListener( this );
		novoButton.addActionListener( this );
		
		nomeText = new JTextField();
		nomeText.setEnabled( false );
		iniciaisText = new JTextField();
		iniciaisText.setEnabled( false );
		checkSuperior = new JCheckBox( "T" + eacute + "cnico Superior" );
		checkSuperior.setEnabled( false );
		JPanel corPanel = new JPanel();
		corPanel.setLayout( new BoxLayout( corPanel, BoxLayout.Y_AXIS ) );
		corGroup = new BetterButtonGroup( false );
		cores = new JRadioButton[ HigieneDataProvider.CORES_TECNICOS.length ];
		for( int n = 0; n < HigieneDataProvider.CORES_TECNICOS.length; n++ )
		{
			cores[ n ] = new JRadioButton( "            " );
			cores[ n ].setBackground( HigieneDataProvider.CORES_TECNICOS[ n ] );
			corPanel.add( cores[ n ] );
			corGroup.add( cores[ n ] );
		}
		JScrollPane corScroll = 
			new JScrollPane( corPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
								JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		
		GridBagLayout gridbag = new GridBagLayout();
		getContentPane().setLayout( gridbag );
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.insets = new Insets( 1, 1, 1, 1 );
		constraints.fill = GridBagConstraints.BOTH;
		constraints.weighty = 1;
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.gridheight = 1;
		
		JPanel upperPanel = new JPanel();
		upperPanel.setLayout( new GridLayout( 1, 2 ) );
		upperPanel.add( scp );
		JPanel textPanel = new JPanel();
		upperPanel.add( textPanel );
		gridbag.setConstraints( upperPanel, constraints );
		getContentPane().add( upperPanel );
		
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.weighty = 0;
		constraints.weightx = 0.3;
		constraints.gridwidth = 1;
		constraints.gridheight = GridBagConstraints.REMAINDER;;
		
		gridbag.setConstraints( novoButton, constraints );
		getContentPane().add( novoButton );
		
		gridbag.setConstraints( okButton, constraints );
		getContentPane().add( okButton );
		
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( cancelarButton, constraints );
		getContentPane().add( cancelarButton );
		
		gridbag = new GridBagLayout();
		textPanel.setLayout( gridbag );
		constraints.weighty = 0;
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.gridheight = 1;
		
		JLabel nomeLabel = new JLabel( "Nome" );
		gridbag.setConstraints( nomeLabel, constraints );
		textPanel.add( nomeLabel );
		
		gridbag.setConstraints( nomeText, constraints );
		textPanel.add( nomeText );
		
		JLabel iniciaisLabel = new JLabel( "Iniciais" );
		gridbag.setConstraints( iniciaisLabel, constraints );
		textPanel.add( iniciaisLabel );
		
		gridbag.setConstraints( iniciaisText, constraints );
		textPanel.add( iniciaisText );
		
		gridbag.setConstraints( checkSuperior, constraints );
		textPanel.add( checkSuperior );
		
		JLabel corLabel = new JLabel( "Cor" );
		gridbag.setConstraints( corLabel, constraints );
		textPanel.add( corLabel );

		constraints.weighty = 1;
		constraints.gridheight = GridBagConstraints.REMAINDER;
		constraints.fill = GridBagConstraints.BOTH;

		gridbag.setConstraints( corScroll, constraints );
		textPanel.add( corScroll );
	
		new CopyPasteHandler( nomeText );
		new CopyPasteHandler( iniciaisText );
	}
	
	@Override
	public void actionPerformed( ActionEvent e )
	{
		if( e.getSource().equals( okButton ) )
		{
			if( save() )
			{
				close();
			}
		}
		else if( e.getSource().equals( cancelarButton ) )
		{
			id = null;
			close();
		}
		if( e.getSource().equals( novoButton ) )
		{
			table.getSelectionModel().removeListSelectionListener( this );
			nomeText.setText( "" );
			iniciaisText.setText( "" );
			corGroup.setIntSelected( 0 );
			nomeText.setEnabled( true );
			iniciaisText.setEnabled( true );
			corGroup.setEnabled( true );
			checkSuperior.setSelected( false );
			checkSuperior.setEnabled( true );
			id = null;
			isNew = true;
		}
	}
	
	@Override
	public void valueChanged( ListSelectionEvent listSelectionEvent )
	{
		int selected = table.getSelectedRow();
		if( selected == -1 )
		{
			return;
		}
		ColumnizedObjectArray row = model.getRowAt( selected );
		id = row.getID();
		String nome = (String) row.getValue( 0 );
		String iniciais = (String) row.getValue( 1 );
		Integer cor = ( Integer ) row.getValue( 2 );
		String superior = ( String) row.getValue( 3 );
		nomeText.setText( nome );
		iniciaisText.setText( iniciais );
		corGroup.setIntSelected( cor.intValue() );
		nomeText.setEnabled( true );
		iniciaisText.setEnabled( true );
		corGroup.setEnabled( true );
		checkSuperior.setEnabled( true );
		checkSuperior.setSelected( superior != null && "y".equals(superior) );
	}
	
	private void close()
	{
		setVisible( false );
		dispose();
	}
	
	public boolean getIsNew()
	{
		return isNew;
	}
	
	public Integer getID()
	{
		return id;
	}
	
	private boolean save()
	{
		String nome = nomeText.getText().trim();
		String nomePlain = com.evolute.utils.strings.StringPlainer.convertString( nome );
		String iniciais = iniciaisText.getText().trim();
		Integer cor = new Integer( corGroup.getIntSelected() );
		if( nome.length() == 0 || iniciais.length() == 0 )
		{
			JOptionPane.showMessageDialog( this, "O Nome e as iniciais n\u00e3o podem ser vazios.", "Erro...", 
				JOptionPane.ERROR_MESSAGE );
			return false;
		}
		try
		{
			MarcacoesTecnicosHstData tecnico;
			if( id != null )
			{
				tecnico = ( MarcacoesTecnicosHstData ) JDO.load( MarcacoesTecnicosHstData.class, id );
			}
			else
			{
				tecnico = new MarcacoesTecnicosHstData();
			}
			tecnico.set( MarcacoesTecnicosHstData.IS_SUPERIOR, checkSuperior.isSelected() ? "y" : "n" );
			tecnico.set( MarcacoesTecnicosHstData.NOME, nome );
			tecnico.set( MarcacoesTecnicosHstData.NOME_PLAIN, nomePlain );
			tecnico.set( MarcacoesTecnicosHstData.INICIAIS, iniciais );
			tecnico.set( MarcacoesTecnicosHstData.IDENTIFICADOR, cor );
			tecnico.save();
			if( id == null )
			{
				id = (Integer)tecnico.get( MarcacoesTecnicosHstData.ID );
			}
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a gravar...", false );
			return false;
		}

		return true;
	}

}
