/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.elasticsearch.search.facet.histogram;

import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexNumericFieldData;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.facet.FacetExecutor;
import org.elasticsearch.search.facet.FacetParser;
import org.elasticsearch.search.facet.FacetPhaseExecutionException;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.Map;

/**
 *
 */
public class HistogramFacetParser extends AbstractComponent implements FacetParser {

    @Inject
    public HistogramFacetParser(Settings settings) {
        super(settings);
        InternalHistogramFacet.registerStreams();
    }

    @Override
    public String[] types() {
        return new String[]{HistogramFacet.TYPE};
    }

    @Override
    public FacetExecutor.Mode defaultMainMode() {
        return FacetExecutor.Mode.COLLECTOR;
    }

    @Override
    public FacetExecutor.Mode defaultGlobalMode() {
        return FacetExecutor.Mode.COLLECTOR;
    }

    @Override
    public FacetExecutor parse(String facetName, XContentParser parser, SearchContext context) throws IOException {
        String keyField = null;
        String valueField = null;
        String keyScript = null;
        String valueScript = null;
        String scriptLang = null;
        Map<String, Object> params = null;
        long interval = 0;
        HistogramFacet.ComparatorType comparatorType = HistogramFacet.ComparatorType.KEY;
        XContentParser.Token token;
        String fieldName = null;
        ScriptService.ScriptType valueScriptType = null;
        ScriptService.ScriptType keyScriptType = null;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                fieldName = parser.currentName();
            } else if (token == XContentParser.Token.START_OBJECT) {
                if ("params".equals(fieldName)) {
                    params = parser.map();
                }
            } else if (token.isValue()) {
                if ("field".equals(fieldName)) {
                    keyField = parser.text();
                } else if ("key_field".equals(fieldName) || "keyField".equals(fieldName)) {
                    keyField = parser.text();
                } else if ("value_field".equals(fieldName) || "valueField".equals(fieldName)) {
                    valueField = parser.text();
                } else if ("interval".equals(fieldName)) {
                    interval = parser.longValue();
                } else if ("time_interval".equals(fieldName) || "timeInterval".equals(fieldName)) {
                    interval = TimeValue.parseTimeValue(parser.text(), null).millis();
                } else if ("order".equals(fieldName) || "comparator".equals(fieldName)) {
                    comparatorType = HistogramFacet.ComparatorType.fromString(parser.text());
                } else if (ScriptService.KEY_SCRIPT_INLINE.match(fieldName)) {
                    keyScript = parser.text();
                    keyScriptType = ScriptService.ScriptType.INLINE;
                } else if (ScriptService.KEY_SCRIPT_ID.match(fieldName)) {
                    keyScript = parser.text();
                    keyScriptType = ScriptService.ScriptType.INDEXED;
                } else if (ScriptService.KEY_SCRIPT_FILE.match(fieldName)) {
                    keyScript = parser.text();
                    keyScriptType = ScriptService.ScriptType.FILE;
                } else if (ScriptService.VALUE_SCRIPT_INLINE.match(fieldName)) {
                    valueScript = parser.text();
                    valueScriptType = ScriptService.ScriptType.INLINE;
                } else if (ScriptService.VALUE_SCRIPT_ID.match(fieldName)) {
                    valueScript = parser.text();
                    valueScriptType = ScriptService.ScriptType.INDEXED;
                } else if (ScriptService.VALUE_SCRIPT_FILE.match(fieldName)) {
                    valueScript = parser.text();
                    valueScriptType = ScriptService.ScriptType.FILE;
                } else if (ScriptService.SCRIPT_LANG.match(fieldName)) {
                    scriptLang = parser.text();
                }
            }
        }

        if (keyScript != null && valueScript != null) {
            return new ScriptHistogramFacetExecutor(scriptLang, keyScript, keyScriptType, valueScript, valueScriptType, params, interval, comparatorType, context);
        }

        if (keyField == null) {
            throw new FacetPhaseExecutionException(facetName, "key field is required to be set for histogram facet, either using [field] or using [key_field]");
        }

        if (interval <= 0) {
            throw new FacetPhaseExecutionException(facetName, "[interval] is required to be set for histogram facet");
        }

        FieldMapper keyMapper = context.smartNameFieldMapper(keyField);
        if (keyMapper == null) {
            throw new FacetPhaseExecutionException(facetName, "No mapping found for key_field [" + keyField + "]");
        }
        IndexNumericFieldData keyIndexFieldData = context.fieldData().getForField(keyMapper);

        IndexNumericFieldData valueIndexFieldData = null;
        if (valueField != null) {
            FieldMapper valueMapper = context.smartNameFieldMapper(valueField);
            if (valueMapper == null) {
                throw new FacetPhaseExecutionException(facetName, "No mapping found for value_field [" + valueField + "]");
            }
            valueIndexFieldData = context.fieldData().getForField(valueMapper);
        }

        if (valueScript != null) {
            return new ValueScriptHistogramFacetExecutor(keyIndexFieldData, scriptLang, valueScript, valueScriptType, params, interval, comparatorType, context);
        } else if (valueField == null) {
            return new CountHistogramFacetExecutor(keyIndexFieldData, interval, comparatorType, context);
        } else if (keyField.equals(valueField)) {
            return new FullHistogramFacetExecutor(keyIndexFieldData, interval, comparatorType, context);
        } else {
            // we have a value field, and its different than the key
            return new ValueHistogramFacetExecutor(keyIndexFieldData, valueIndexFieldData, interval, comparatorType, context);
        }
    }
}
