package comHttp;

import java.io.*;
import java.util.*;

public class LeitorHtml{

  //Palavras chave para achar o valor de uma variável.
  private static String INPUT = "input";
  private static String NAME = "name";
  private static String VALUE = "value";
  private static String FIM_DE_INPUT = ">";
  //Separadores de tokens.
  private static String SEPARADORES = " =<\t\n\r\f\"\'";

  //Entrada do html.
  private BufferedReader html;

  public LeitorHtml(InputStream in){

    html = new BufferedReader(new InputStreamReader(in));
  }


  //Procura todas as variáveis e coloca numa tabela de properties.
  public Properties procuraVariaveis() throws IOException{

    Properties vars = new Properties();
    StringTokenizer tokens;
    StringTokenizer tokensInput;
    String token;
    String nome = null, valor = null;

    String codigo = "";
    String linha = "";
    do{
      codigo += " " + linha;
      linha = html.readLine();
    }while(linha != null);

    tokens = new StringTokenizer(codigo, SEPARADORES);

    while( tokens.hasMoreTokens() ){//w0

      //Se achar a palavra chave INPUT.
      if( tokens.nextToken(SEPARADORES).equalsIgnoreCase(INPUT) &&
          tokens.hasMoreTokens() ){//i0

       tokensInput = new StringTokenizer(tokens.nextToken(FIM_DE_INPUT)+ FIM_DE_INPUT,
                                    SEPARADORES, true);


       do{//Procura o nome e o valor da variável.
         token = tokensInput.nextToken(SEPARADORES);
         System.out.println(token + "****\n");


         if( token.equalsIgnoreCase(NAME) &&
             tokensInput.hasMoreTokens() ){

           tokensInput.nextToken("\"\'");
           nome = tokens.nextToken();
           System.out.println(nome + "###\n");
           if("\"\'".indexOf(nome) != -1)
             nome = null;
         }

         else if( token.equalsIgnoreCase(VALUE) &&
             tokensInput.hasMoreTokens() ){

           tokensInput.nextToken("\"\'");
           valor = tokensInput.nextToken("\"\'");
           System.out.println(valor + "@@@\n");
           if("\"\'".indexOf(valor) != -1)
             valor = null;
         }

       }while(nome == null || valor == null || !token.equals(FIM_DE_INPUT) );

       if(nome != null) vars.setProperty(nome, valor);

       nome = null;
       valor = null;
      }//i0
    }//w0

    return vars;
  }
}
