/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package usda.weru.gis.data;

import org.apache.log4j.Logger;
import org.geotools.data.FeatureSource;
import org.geotools.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.Country;

/**
 *
 * @author Joseph Levin <joelevin@weru.ksu.edu>
 */
public class SiteCountryLevelLookup extends AbstractLookup<Site.Country>{
    private static final Logger LOGGER = Logger.getLogger(SiteCountryLevelLookup.class);

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

    @Override
    protected Country 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.Country) Site.valueOfFIPS(countryFips);
    }

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

    @Override
    protected Filter createFilter(final Hints hints, final FilterFactory2 factory, final FeatureSource source, final Site.Country 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) {
        if(hasColumn(source, COLUMN_CNTRY_NAME, String.class) && hasColumn(source, COLUMN_FIPS_CNTRY, String.class)){
            //this this is a country source
            return true;
        }
        else{
            return false;
        }
    }

}
