package com.softgraf.model;

import static javax.swing.JOptionPane.ERROR_MESSAGE;
import static javax.swing.JOptionPane.showMessageDialog;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

// 25
// Propriedades dos componentes swing
public class ComponenteProperties {

	private String arqConfig;
	private Properties tabela;

	// "arquivo".properties
	public ComponenteProperties(String arqConfig) {
		this.arqConfig = arqConfig;
		// instancia um Hashtable persistente
		this.tabela = new Properties();
		
		// le propriedades do arquivo para a tabela
		if (new File(arqConfig).exists())
			lerPropriedades();
	}

	// le conteúdo da tabela a partir de arqConfig
	private void lerPropriedades()  {
		try {
			FileInputStream entrada = new FileInputStream(arqConfig);
			tabela.load(entrada);
			entrada.close();
		} catch (IOException e) {
			e.printStackTrace();
			showMessageDialog(null, "Não pode ler o arquivo:\n" + arqConfig, "ComponenteProperties", ERROR_MESSAGE);
		}
	}

	// salva o conteúdo da tabela no arquivo arqConfig
	public void salvarPropriedades() {
		try {
			FileOutputStream saida = new FileOutputStream(arqConfig);
			tabela.store(saida, "Propriedades de Componentes da Tela");
			saida.close();
		} catch (IOException e) {
			e.printStackTrace();
			showMessageDialog(null, "Não pode salvar o arquivo:\n" + arqConfig, "ComponenteProperties", ERROR_MESSAGE);
		}
	}
	
	public void setValor(String id, Point xy) {
		String x = String.valueOf(xy.x);
		String y = String.valueOf(xy.y);
		tabela.setProperty(id, x + "," + y);
	}
	
	public void setValor(String id, Dimension dim){
		setValor(id, new Point(dim.width, dim.height));
	}
	
	public Point getPoint(String id) {
		String valor = tabela.getProperty(id);
		if (valor != null) {
			String[] valores = valor.split(",");
			return new Point(Integer.valueOf(valores[0]),
					Integer.valueOf(valores[1]));
		}
		
		return null;
	}
	
	public Dimension getDim(String id){
		Point p = getPoint(id);
		if (p != null)
			return new Dimension(p.x, p.y);
		else
			return null;
	}
	
	public void setValor(String id, Color cor){
		String valor = cor.getRed() + "," + cor.getGreen() + "," + cor.getBlue();
		tabela.setProperty(id, valor);
	}
	
	public Color getCor(String id){
		String valor = tabela.getProperty(id);
		if (valor != null){
			String rgb[] = valor.split(",");
			return new Color(Integer.valueOf(rgb[0]), Integer.valueOf(rgb[1]), Integer.valueOf(rgb[2]));
		}
		
		return null;
	}
	
	public boolean isEmpty(){
		return tabela.isEmpty();
	}

}
