/* $Id: SpreadSelector.java 125 2011-03-09 09:49:51Z ohura $ */
package smart_gs.spread_selection;

import smart_gs.logical.Spread;
import java.util.List;
import java.util.ArrayList;

public class SpreadSelector {

	private String spreadSelection;
	private List<Spread> allSpreads;
	private List<int[]> indexes;

	public SpreadSelector(List<Spread> spreads, String spreadSelection) {
		this.allSpreads = spreads;
		this.spreadSelection = spreadSelection;
		this.indexes = new ArrayList<int[]>();
		makeSelectIndex();
	}
	

	/**
	 * 検索対象のページのリストを作る
	 */
	public void makeSelectIndex() {
		String[] strAry = spreadSelection.split(",");
		for (int i = 0; i < strAry.length; i++) {
			String[] strIndex = strAry[i].split("-");
			// 3-10など、範囲を指定された場合
			if (strIndex.length == 2) {
				int[] index = { Integer.parseInt(strIndex[0].trim()),
						Integer.parseInt(strIndex[1].trim()) };
				if (!wasAdded(index)) {
					this.indexes.add(index);
				}
			}
			// 4, 5、など、indexがひとつだけ指定された場合
			else {
				int[] index = {Integer.parseInt(strIndex[0].trim())};
				if (!wasAdded(index)) {
					this.indexes.add(index);
				}
			}
		}
	}

	/**
	 * 検索するページ（スプレッド）を求めるメソッド。
	 * 
	 * @return
	 */
	public List<Spread> select() {
		List<Spread> spreads = new ArrayList<Spread>();
		for (int i = 0; i < this.indexes.size(); i++) {
			SpreadFilter spreadFilter = new SpreadFilter(allSpreads);
			if (indexes.get(i).length == 2) {
				spreadFilter.filter(indexes.get(i)[0], indexes.get(i)[1]);
			} else {
				spreadFilter.filter(indexes.get(i)[0]);
			}
			for (int j = 0; j < spreadFilter.getFilterdSpreads().size(); j++) {
				spreads.add(spreadFilter.getFilterdSpreads().get(j));
			}
		}
		return spreads;
	}

	/*
	 * indexが重複してるか調べるメソッド。
	 * ただ、1,2,3,4,5などを入力されたのには対応できない！
	 */
	public boolean wasAdded(int[] index) {
		for (int i = 0; i < this.indexes.size(); i++) {
			if (this.indexes.get(i).length == 2) {
				if (index.length == 2) {
					if (index[1] < this.indexes.get(i)[0]
							|| this.indexes.get(i)[1] < index[0]) {
						return false;
					} else {
						return true;
					}
				} else {
					return this.indexes.get(i)[0] <= index[0]
							&& index[0] <= this.indexes.get(i)[1];
				}
			} else {
				if (index.length == 2) {
					return index[0] <= this.indexes.get(i)[0]
							&& this.indexes.get(i)[0] <= index[1];
				} else {
					return this.indexes.get(i)[0] == index[0];
				}
			}
		}
		return false;
	}
}
