/* XSSFCustomFilters.java

	Purpose:
		
	Description:
		
	History:
		May 11, 2016 10:44:59 AM, Created by henrichen

	Copyright (C) 2016 Potix Corporation. All Rights Reserved.
*/

package org.zkoss.poi.xssf.usermodel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCustomFilter;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCustomFilters;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFilterColumn;
import org.zkoss.poi.ss.usermodel.CustomFilter;
import org.zkoss.poi.ss.usermodel.CustomFilters;
import org.zkoss.poi.ss.usermodel.CustomFilter.Operator;
import org.zkoss.poi.xssf.usermodel.XSSFAutoFilter.XSSFFilterColumn;

//ZSS-1224
/**
 * @author henri
 * @since 3.9.11
 */
public class XSSFCustomFilters implements CustomFilters, Serializable {
	private CTCustomFilters _ctFilters;
	private List<XSSFCustomFilter> _filters;
	
	XSSFCustomFilters(CTCustomFilters ctFilters) {
		_ctFilters = ctFilters;
		_filters = new ArrayList<XSSFCustomFilter>();
		if (_ctFilters != null) {
			for (CTCustomFilter filter : _ctFilters.getCustomFilterList()) {
				_filters.add(new XSSFCustomFilter(filter));
			}
		}
	}
	
	public XSSFCustomFilters(XSSFFilterColumn  fc) {
		CTFilterColumn ctfc = fc.getCTFilterColumn();
		if (ctfc.isSetCustomFilters()) {
			ctfc.unsetCustomFilters();
		}
		_ctFilters = ctfc.addNewCustomFilters();
		_filters = new ArrayList<XSSFCustomFilter>();
	}
	
	@Override
	public boolean isAnd() {
		return _ctFilters.isSetAnd() && _ctFilters.getAnd();
	}

	@Override
	public CustomFilter getCustomFilter1() {
		return _filters.get(0);
	}

	@Override
	public CustomFilter getCustomFilter2() {
		return _filters.size() > 1 ? _filters.get(1) : null;
	}
	
	//for export
	public void setAnd(boolean and) {
		if (and) {
			_ctFilters.setAnd(and);
		} else {
			_ctFilters.unsetAnd(); // default to OR
		}
	}
	
	//for export
	public void addCustomFilter(Operator operator, String value) {
		CTCustomFilter ctFilter = _ctFilters.addNewCustomFilter();
		XSSFCustomFilter filter = new XSSFCustomFilter(ctFilter);
		filter.setProperties(operator, value);
		_filters.add(filter);
	}
}
