import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import util.Log;

import map.data.City;
import map.store.ChainStore;

/**
 * TSUTAYAの店舗情報を取得するクラスです。
 * 
 * @author Masayasu Fujiwara
 */
public class TsutayaPlugin extends ChainStore {
	
	/**
	 * 住所切り出しパターン
	 */
	private final Pattern ADDRESS_PARSER;

	/**
	 * 読み込み状態
	 */
	private boolean parseState;

	public TsutayaPlugin() {
		super("TSUTAYA", "SJIS");
		this.ADDRESS_PARSER = Pattern.compile("〒\\d{3}-\\d{4}");
	}

	@Override
	protected URL getURL(City city, int page) {
		URL url = null;
		if (page == 1) {
			try {
				url =  new URL("http://www.tsutaya.co.jp/shop/dis-l.zhtml?PREF=" + (city.getCode() / 1000) + "&TXT_CITY=" + URLEncoder.encode(city.getName(),  this.ENCODING) + "&FROM=1&TO=20");
			} catch (Exception e) {
				Log.err(this, e);
			}
		}
		return url;
	}

	@Override
	protected String parseAddress(String input) {
		Matcher matcher = this.ADDRESS_PARSER.matcher(input);
		if (matcher.find()) {
			this.parseState = true;
		} else if (this.parseState){
			this.parseState = false;
			return input.replaceAll("\\s", "");
		}
		return null;
	}
}
