/*
 * Copyright 2007 nori090
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lib2chj.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import lib2chj.struct.HTTP_DATA;
import lib2chj.struct.Ita;
import lib2chj.struct.Server;
import lib2chj.struct.Subject;
import lib2chj.struct.Thread;

/**
 * 2chのsubject.txtを構造体に押し込む仕事
 * 
 * @author nori090
 * @version $Rev: 19 $ $Date: 2008-03-25 22:46:11 +0900 (Tue, 25 Mar 2008) $
 */
public class SubjectBuilder {
    Map<String, Server> server_map;

    public SubjectBuilder() {
        super();
        this.server_map = new HashMap<String, Server>();
    }

    public SubjectBuilder( Map<String, Server> m ) {
        super();
        if ( m == null )
            throw new NullPointerException( "map is null !" );
        this.server_map = m;
    }

    public SubjectBuilder get( String url )
        throws IOException {
        Ita ita = _init( url );
        HTTP_DATA data = new HTTP_DATA().setUrl( ita.getUrl() + "/subject.txt" );
        BufferedReader br = HttpHelper.http_get( data );
        if ( br != null ) {
            String line = null;
            while ( ( line = br.readLine() ) != null ) {
                String[] s = ParseUtil.split_subject( line );
                String thread_id = s[0].substring( 0, ( s[0].length() - ".dat".length() ) );
                Subject subject = ita.getSubject( thread_id );
                if ( subject == null ) {
                    subject = new Subject( ita );
                }
                subject.setId( thread_id );
                subject.setTitle( s[1] );
                subject.setUrl( ita.getUrl() + "/subject.txt" );
                subject.setCommentCount( Integer.parseInt( s[2] ) );
                Thread thread = ita.getThread( thread_id );
                if ( thread == null ) {
                    thread = new Thread( ita );
                }
                thread.setId( thread_id );
                thread.setSubject( subject );
                thread.setTitle( s[1] );
                thread.setUrl( ita.getUrl() + "/dat/" + s[0] );
                subject.setThread( thread );
                ita.putSubject( subject );
                ita.putThread( thread );
            }
            br.close();
        }
        return this;
    }

    /**
     * 初期化。
     */
    Ita _init( String s_url ) {
        URL url = null;
        try {
            url = new URL( s_url );
        }
        catch ( MalformedURLException e ) {
            e.printStackTrace();
            throw new RuntimeException( e );
        }
        Server serv = server_map.get( url.getHost() );
        if ( serv == null ) {
            serv = new Server();
        }
        serv.setServerName( url.getHost() );
        server_map.put( serv.getServerName(), serv );
        String ita_name = HttpHelper._split_ita_name_at_path( url.getPath() );
        if ( ita_name == null )
            throw new RuntimeException( "unknown ita name" );
        if ( serv.getItaMap() == null ) {
            serv.setItaMap( new HashMap<String, Ita>() );
        }
        Ita ita = serv.getIta( ita_name );
        /*
         * subject.txtは、http getしたときに、一応、更新順序で並んでいるみたいなので、 LinkedHashMapとしてみる。（列挙するときに順序を持たせる）
         */
        if ( ita == null ) {
            ita = new Ita( serv );
            ita.setItaName( ita_name );
            ita.setUrl( url.getProtocol() + "://" + url.getHost() + "/" + ita_name );
            ita.setSubjects( new LinkedHashMap<String, Subject>() );
            ita.setThreads( new LinkedHashMap<String, Thread>() );
            serv.putIta( ita );
        }
        return ita;
    }

    public Map<String, Server> toMap() {
        return server_map;
    }
}
