/*
 * Copyright 2004-2014 ICEsoft Technologies Canada Corp.
 *
 * Licensed 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.icefaces.ace.component.list;

import org.icefaces.ace.json.JSONArray;

import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class FilterState {
    Map<ACEList, String> valueMap = new HashMap<ACEList, String>();

    public FilterState() {}

    /* Create comprehensive current filter state */
    public FilterState(ACEList list) {
		saveState(list);
    }

    /* Create delta state from incoming filter input */
    public FilterState(FacesContext context, ACEList list) {
        String clientId = list.getClientId(context);
        Map<String,String> params = context.getExternalContext().getRequestParameterMap();

		if (list.getFilterFacet() != null) return;

		String filterId = list.getClientId(context) + "_filter";
		saveState(list, params.get(filterId));
    }

    public void saveState(ACEList list) {
		Object filterValues = list.getFilterValues();
		if (filterValues != null) {
			if (filterValues instanceof Collection || Object[].class.isAssignableFrom(filterValues.getClass())) {
				JSONArray jsonArray = null;
				try {
					if (filterValues instanceof Collection) jsonArray = new JSONArray((Collection) filterValues);
					else jsonArray = new JSONArray(filterValues);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (jsonArray != null) valueMap.put(list, jsonArray.toString());
			} else {
				throw new FacesException("Attribute filterValues in ace:list with ID '" + list.getId() + "' must be either a Collection or an array of strings.");
			}
		} else {
			valueMap.put(list, list.getFilterValue());
		}
    }

    public void saveState(ACEList list, String value) {
        valueMap.put(list, value);
    }

    private void restoreState(ACEList list) {
		String val = valueMap.get(list);
		if (val != null)
			list.setFilterValue(val);
    }

    public void apply(ACEList list) {
		restoreState(list);
    }
}
