/*
 * Paraselene
 * Copyright (c) 2009, 2010  Akira Terasaki
 * このファイルは同梱されているLicense.txtに定めた条件に同意できる場合にのみ
 * 利用可能です。
 */
package paraselene.tool;

import paraselene.supervisor.*;
import java.util.*;
import java.io.*;

public class MipFile {
	private static Object	dmy = new Object();
	private static volatile boolean init_f = false;
	private static IP[]	ip_list = new IP[0];

	private MipFile(){}

	public static boolean isInit() {
		return init_f;
	}

	public static void init( String dir ) {
		if ( dir == null )	return;
		dir = dir.trim();
		if ( dir.isEmpty() )	return;
		synchronized( dmy ) {
			if ( init_f )	return;
			init_f = true;
			try {
				ArrayList<IP>	ip = new ArrayList<IP>();
				File[]	files = new File( dir ).listFiles();
				for ( int i = 0; i < files.length; i++ ) {
					if ( !files[i].isFile() )	continue;
					String	name = files[i].getName();
					String[]	part = name.split( "\\." );
					if ( part.length != 2 )	continue;
					if ( !"mip".equals( part[1] ) )	continue;
					RequestParameter.Mobile	mob = RequestParameter.Mobile.valueOf( part[0] );
					if ( mob == null )	continue;

					BufferedReader	r = new BufferedReader( new FileReader( files[i] ) );
					while ( true ) {
						String	line = r.readLine();
						if ( line == null )	break;
						ip.add( new IP( mob, line ) );
					}
					r.close();
				}
				ip_list = ip.toArray( new IP[0] );
			}
			catch( Exception e ) {
				e.printStackTrace();
				Option.debug( e );
			}
		}
	}

	public RequestParameter.Mobile judgeMobile( String ip ) {
		for ( int i = 0; i < ip_list.length; i++ ) {
			if ( ip_list[i].isHit( ip ) )	return ip_list[i].mobile;
		}
		return RequestParameter.Mobile.NO_MOBILE;
	}

}

