/*
 * 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.StateEquivalent;

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

    public static final String COLUMN_STATE_D00_= "ST99_D00_";
    public static final String COLUMN_STATE_D00_I= "ST99_D00_I";
    public static final String COLUMN_STATE_NAME= "NAME";
    public static final String COLUMN_STATE_STATE = "STATE";

    @Override
    protected StateEquivalent create(FeatureSource source, Feature feature) {
        String stateCode = getValue(feature, COLUMN_STATE_STATE, String.class);

        if(stateCode == null){
            return null;
        }

        stateCode = stateCode.trim();

        assert stateCode.length() == 2;

        String fips = "US" + stateCode;

        return (Site.StateEquivalent) Site.valueOfFIPS(fips);
    }

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

    @Override
    protected Filter createFilter(final Hints hints, final FilterFactory2 factory, final FeatureSource source, final Site.StateEquivalent state){
        try{
            String stateCode = state.getFIPS();
            //returns features that match the state and county
            String cql = COLUMN_STATE_STATE + " = '" + stateCode + "'";
            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_STATE_STATE, String.class) && hasColumn(source, COLUMN_STATE_D00_, Long.class) && hasColumn(source, COLUMN_STATE_D00_I, Long.class)){
            return true;
        }
        else{
            return false;
        }
    }

}
