package usda.weru.gis.data;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; 
import org.geotools.data.FeatureSource;
import org.geotools.util.factory.Hints;
import org.geotools.filter.text.cql2.CQL;
import org.geotools.filter.text.cql2.CQLException;
import org.opengis.feature.Feature;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import usda.weru.weps.location.Site;
import usda.weru.weps.location.Site.Level0;

/**
 *
 * @author Joseph Levin <joelevin@weru.ksu.edu>
 */
public class SiteCountryLevelLookup extends AbstractLookup<Site.Level0> {

    private static final Logger LOGGER = LogManager.getLogger(SiteCountryLevelLookup.class);

    public static final String COLUMN_CNTRY_NAME = "CNTRY_NAME";
    public static final String COLUMN_FIPS_CNTRY = "FIPS_CNTRY";

    @Override
    protected Level0 create(FeatureSource<?, ?> source, Feature feature) {
        String countryFips = getValue(feature, COLUMN_FIPS_CNTRY, String.class);

        if (countryFips.length() == 2) {
            countryFips = countryFips + "00";
        }

        //just have a lookup the constant by the fips
        return (Site.Level0) Site.valueOfFIPS(countryFips);
    }

    @Override
    protected Class<Level0> getSupportedClass() {
        return Site.Level0.class;
    }

    @Override
    protected Filter createFilter(final Hints hints, final FilterFactory2 factory,
            final FeatureSource<?, ?> source, final Site.Level0 country) {
        try {
            String countryCode = country.getFIPSChar2();
            //returns features that match the state and county
            String cql = COLUMN_FIPS_CNTRY + " = '" + countryCode + "'";
            Filter filter = CQL.toFilter(cql);
            return filter;
        } catch (CQLException ce) {
            LOGGER.warn("Unable to create CQL query.", ce);
            return null;
        }
    }

    @Override
    protected boolean supports(FeatureSource<?, ?> source) {
        return hasColumn(source, COLUMN_CNTRY_NAME, String.class)
                && hasColumn(source, COLUMN_FIPS_CNTRY, String.class);
    }

}
