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.Level1;

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

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

    public static final String COLUMN_NAME_0 = "NAME_0";
    public static final String COLUMN_ID_1 = "ID_1";
    public static final String COLUMN_NAME_1 = "NAME_1";
    public static final String COLUMN_HASC_1 = "HASC_1";

    @Override
    protected Level1 create(FeatureSource<?, ?> source, Feature feature) {
        String hasc = getValue(feature, COLUMN_HASC_1, String.class);

        if (hasc == null || hasc.trim().isEmpty()) {
            return null;
        }

        hasc = hasc.trim();

        return (Site.Level1) Site.valueOfHASC(hasc);
    }

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

    @Override
    protected Filter createFilter(final Hints hints, final FilterFactory2 factory,
            final FeatureSource<?, ?> source, final Site.Level1 site) {
        try {

            String hasc = site.getHASC();

            if (hasc == null || hasc.isEmpty()) {
                LOGGER.debug("Unable to create CQL query for site without hasc code.");
                return null;
            }

            //returns features that match the state and county
            String cql = COLUMN_HASC_1 + " = '" + hasc + "'";
            Filter filter = CQL.toFilter(cql);
            return filter;
        } catch (CQLException ce) {
            LOGGER.warn("Unable to create CQL query for HASC shapefile.", ce);
            return null;
        }
    }

    @Override
    protected boolean supports(FeatureSource<?, ?> source) {
        return hasColumn(source, COLUMN_NAME_0, String.class)
                && hasColumn(source, COLUMN_NAME_1, String.class)
                && hasColumn(source, COLUMN_ID_1, Integer.class)
                && hasColumn(source, COLUMN_HASC_1, String.class);
    }

}
