package view.definition;

import controller.definition.Definition_Frame_Controller;
import net.miginfocom.swing.MigLayout;
import org.sig.fw.database.model.DBModel;
import org.sig.fw.db.corrida.dao.Definition_DBAO;
import org.sig.fw.db.corrida.model.Definition;
import org.sig.fw.layout.component.SLabel;
import org.sig.fw.layout.component.STextField;
import org.sig.fw.layout.pane.SOptionPane;
import table.search.Search_Definition_Table;
import view.Definition_Frame_View;

import java.util.ArrayList;

public class Definition_View extends Definition_Frame_View 
{
	private static final long serialVersionUID = -4640562421963912343L;
	
	private String family = "";
	private String text = "";
	private STextField jtf_texte;
	
	public Definition_View(Definition_Frame_Controller ctrl_definition, String family, String text)
	{
		super(ctrl_definition, "");
		if(family.equals(Definition_DBAO.FACT_CATEGORY))
			this.setTitle("Liste des catégories de factures");
		else
			this.setTitle("Liste des types de paiements");
		setBounds(100, 100, 800, 389);
		
		this.family = family;
		this.text = text;
		
		jp_form.setLayout(new MigLayout("", "[grow][grow][]", "[][][][grow][][][][grow][][grow][]"));
		
		jl_title = new SLabel("Ajouter un <ACTION>", SLabel.TYPE_TITLE_BOLD);
		jp_form.add(jl_title, "cell 0 0 3 1,alignx center");
		
		jp_form.add(jb_validate, "cell 0 10 3 1,alignx center");
		
		SLabel lblNewLabel_2 = new SLabel("Texte", SLabel.TYPE_COMMUN);
		jp_form.add(lblNewLabel_2, "cell 0 2,alignx left");
		
		jtf_texte = new STextField("");
		jp_form.add(jtf_texte, "cell 1 2 2 1,growx");
		jtf_texte.setColumns(10);
		
		configure();
		updateTable();
	}
	
	@Override
	public void updateTable()
	{
		jt_table.setModel(new Search_Definition_Table(new ArrayList<DBModel>(new Definition_DBAO("d").getAllWithFamily(family))));
		jt_table.configureColumn(0, 0, 0, 0);
	}
	
	@Override
	public void configure()
	{
		Definition definition = (Definition) model;
		if(definition == null)
		{
			jl_title.setText("Ajouter " + text);
			jtf_texte.setText("");
		}
		else
		{
			jl_title.setText("Modifier " + text);
			jtf_texte.setText(definition.getName());
		}
	}
	
	@Override
	public String verification()
	{
		String error = "";
		
		if(jtf_texte.getText().isEmpty())
			error += "'Texte' ne peut être vide !\n";
		return error;
	}
	
	@Override
	public void validation() {
		if(verification().isEmpty()) {
			Definition definition = (Definition) model;
			
			if(definition == null) {
				definition = new Definition(-1, family, -1, "");
			}
			
			definition.setName(jtf_texte.getText());

			ctrl_definition.save(definition);
			model = null;
			updateTable();
			configure();
		} else {
			SOptionPane.showErrorMessage("Erreur", verification());
		}
	}
}
