/*
 * NovedadMSASDepMunDep.java
 *
 * Created on 29 de mayo de 2007, 02:49 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.fidufosyga.rules;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fidufosyga.context.Context;

/**
 * 
 * @author JSolano
 */
public class NovedadMSASDepMunDep extends AbstractRule {

	private Pattern pattern;

	public void setParams(Object[] params) {
		String patternStr = (String) params[4];
		pattern = Pattern.compile(patternStr);
		super.setParams(params);
	}

	public boolean performValidation(String field, String registro[],
			String nombreArchivo) {
		String codigoNovedad = registro[new Integer((String) getParams()[0])
				.intValue()];

		if (codigoNovedad.equals((String) getParams()[1])) {
			if (registro[new Integer((String) getParams()[2]).intValue()]
					.equals(getParams()[3])) {

				Matcher matcher = pattern.matcher(field);
				if (!matcher.find()) {
					return true;
				}

				try {
					int numero = 0;
					numero = Integer.parseInt(field);
					return false;
				} catch (Exception e) {

					String codigoDepto = field.substring(0, 2);
					String codigoMun = field.substring(2, 5);
					if (Context.getContext().getAttribute(codigoDepto) == null) {
						Properties defaultProps = new Properties();
						FileInputStream in;

						try {
							File file = new File(System.getProperty("user.dir")
									+ File.separator + "departamentos"
									+ File.separator + codigoDepto
									+ ".properties");
							if (file.exists()) {
								in = new FileInputStream(
										System.getProperty("user.dir")
												+ File.separator
												+ "departamentos"
												+ File.separator + codigoDepto
												+ ".properties");
								defaultProps.load(in);
								in.close();
								Context.getContext().addAttribute(codigoDepto,
										defaultProps);
							} else {
								return true;
							}

						} catch (FileNotFoundException ex) {

							return true;
						} catch (IOException ex) {

							return true;

						}

					}
					if (((Properties) Context.getContext().getAttribute(
							codigoDepto)).getProperty(codigoMun) == null) {
						return true;
					}
					return false;

				}

			}
		}
		return false;
	}

}
