package org.coderepos.nori090;

import static org.coderepos.nori090.PeerCastChecker.YPs;
import static org.coderepos.nori090.PeerCastChecker.getIndexTxtAtProxy;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ContactUrlCollector
    extends Thread
    implements ShutdownListener {
    private static String tmpdir;

    private static final String fname = "org.coderepos.nori090.ContactUrlCollector";

    static volatile Map<String, String> currentMap = null;
    static {
        currentMap = file_read();
    }

    static Object lockbox = new Object();

    @Override
    public void run() {
        try {
            while ( true ) {
                Thread.sleep( ( 60 * 1000 ) * 10 );
                buildNewMap();
            }
        }
        catch ( InterruptedException e ) {
            e.printStackTrace();
        }
    }

    public static void buildNewMap() {
        synchronized ( lockbox ) {
            Map<String, String> newMap = new HashMap<String, String>( currentMap );
            for ( String u : YPs ) {
                List<String> l = getIndexTxtAtProxy( u );
                if ( l != null ) {
                    for ( String s : l ) {
                        String[] c = s.split( "<>" );
                        if ( !"".equals( c[3] ) && !c[0].endsWith( " (切断)" )) {
                            newMap.put( c[0], c[3] );
                        }
                    }
                }
            }
            currentMap = newMap;
        }
    }

    public static List<String> searchContactUrl( String key ) {
        Map<String, String> m = currentMap;
        ArrayList<String> list = new ArrayList<String>();
        Pattern p = Pattern.compile( key );
        for ( String user : m.keySet() ) {
            Matcher match = p.matcher( user );
            if ( match.find() ) {
                list.add( user + "<>" + m.get( user ) );
            }
        }
        return list;
    }

    @SuppressWarnings( "unchecked" )
    public static Map<String, String> getMap() {
        Map<String, String> m = currentMap;
        Map<String, String> m2 = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream( bos );
            oos.writeObject( m );
            ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( bos.toByteArray() ) );
            m2 = (Map<String, String>) ois.readObject();
        }
        catch ( IOException e ) {
            e.printStackTrace();
        }
        catch ( ClassNotFoundException e ) {
            e.printStackTrace();
        }
        return ( m2 );
    }

    private static Map<String, String> file_read() {
        try {
            File f = new File( getTempDir() + fname );
            if ( f.exists() ) {
                HashMap<String, String> m = new HashMap<String, String>();
                BufferedReader br = new BufferedReader( new FileReader( f ) );
                String s = null;
                while ( ( s = br.readLine() ) != null ) {
                    String[] ss = s.split( "<>" );
                    m.put( ss[0], ss[1] );
                }
                br.close();
                return m;
            }
        }
        catch ( Exception e ) {
            e.printStackTrace();
        }
        return new HashMap<String, String>();
    }

    public static void file_out() {
        try {
            Map<String, String> m = getMap();
            File f = new File( getTempDir() + fname );
            FileWriter fw = new FileWriter( f );
            for ( String k : m.keySet() ) {
                fw.write( k + "<>" + m.get( k ) + "\r\n" );
            }
            fw.flush();
            fw.close();
        }
        catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    private static String getTempDir() {
        if ( tmpdir == null ) {
            tmpdir = System.getProperty( "java.io.tmpdir" );
            if ( File.separator.equals( "\\" ) ) {
                tmpdir = tmpdir.replaceAll( "\\\\", "/" );
            }
        }
        return tmpdir;
    }

    @Override
    public boolean shutdown( ShutdownThread resource ) {
        file_out();
        return true;
    }

    @Override
    public String getProcessName() {
        return getClass().getSimpleName();
    }
    
    public static void main( String[] args ) {
        System.out.println(getTempDir());
    }
}
