package Route;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.TextField;
import java.awt.Toolkit;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import org.alov.map.Carte;
import org.alov.map.CarteHost;
import org.alov.map.CarteHostListener;
import org.alov.map.MapUtils;
import org.alov.map.StatusListener;

import org.alov.viewer.FrameAlign;

import org.alov.util.XmlElement;
import org.alov.util.XmlConst;
import org.alov.util.XmlUtils;
import org.alov.util.Const;
import org.alov.util.Strings;

/**
 * Search dialogue.
 */
 
 
 /*
 <object name="btn_search_2" type="button" caption="Shortest Path" bounds="2,16,135,20" /> 
  </object>
<object class="sample.FrameSearch" button="btn_search_2" bounds="0,0,260,170" backcolor="255:255:255">
  <object type="label" name="lbl1" caption="From" bounds="20,30,120,20" /> 
  <object type="textfield" name="fld_name" bounds="150,33,105,20" /> 
  <object type="label" name="lbl2" caption="To" bounds="20,60,120,20" /> 
  <object type="textfield" name="fld_pop" bounds="150,62,105,20" /> 
  <object type="button" name="btn_ok" caption="Shortest path" bounds="70,110,68,20" /> 
  <object type="button" name="btn_cancel" caption="Close" bounds="140,110,40,20" /> 
  </object>
  
  */
public class route extends FrameAlign implements ActionListener,CarteHostListener,StatusListener {

  private static final String BTN_OK      	  	 = "btn_ok";
  private static final String BTN_CANCEL         = "btn_cancel";

  private static final String SEARCH_QUERY_STRING = "searchquery";
  private static final String SEARCH_LAYER_STRING = "searchlayer";

  private String invoke_button_name = null;

  private Carte map = null;
  private CarteHost host = null;

  private String searchLayer = null;
  private String queryString = null;

  private WindowEventHandler wind_handler;
  private boolean isLayoutInvalid = false;

  
  
  
  private void select(){
  
    
  }
  
  
  
  /**
   * Search method
   */
	private void search() {

   String sQuery = null;

   if(!Strings.isNullOrBlank(queryString)){

    //
    // search string is defined in layout file, it is parsed and
    // values are substituted with values of text fields
    //

		int iBegin = queryString.indexOf( '[', 0 );
		int iEnd = queryString.indexOf( ']', 0 );
		int iOld = 0;
    String fieldName = null;

		while ( ( iBegin != -1 ) && ( iEnd != -1 ) && ( iBegin < iEnd ) ) {

			fieldName = queryString.substring( iBegin + 1, iEnd ).trim();
      TextField searchField = ( TextField )MapUtils.findComp( ( Container )this, fieldName );

      if ( searchField != null) {

        sQuery += queryString.substring( iOld, iBegin ) + searchField.getText();
				iOld = iEnd + 1;

      } else {

        isLayoutInvalid = true;

         //error message
        map.proxy.addStatusInfo( Const._ERR_LAYOUT, null,
            "The textedit with name " +
            queryString.substring( iBegin + 1, iEnd ).trim() +
            " is not found in the layout for FrameSearch " + getName() );
        map.broadcastMessage( -1, null );
        return;
      }

			iBegin = queryString.indexOf( '[', iEnd + 1 );
			iEnd = queryString.indexOf( ']', iEnd + 1 );
		}
  	sQuery += queryString.substring( iOld );

   }else{

      searchLayer = map.getActiveLayer().id;

      String sQuery1 = getField("fld_name");
      String sQuery2 = getField("fld_pop");

      if(!Strings.isNullOrBlank(sQuery1)){
            sQuery = "(NAME LIKE '%"+sQuery1+"%')";
      }

      if(!Strings.isNullOrBlank(sQuery2)){
          if (searchLayer.equalsIgnoreCase("Cities"))
              sQuery2 = "(POPULATION >"+sQuery2+")";
         else
              sQuery2 = "(POP2001 >"+sQuery2+")";

         sQuery = (Strings.isNullOrBlank(sQuery)) ? sQuery2
                   : sQuery + " AND " + sQuery2;
      }

   }

    if (!Strings.isNullOrBlank(sQuery)) {
      map.searchAttribute( searchLayer, sQuery, Carte.SEARCH_WHERE );
    }
	}

  String getField(String name){
      TextField searchField = (TextField)MapUtils.findComp((Container)this, name);
      return ( searchField != null) ? searchField.getText() : null;
  }


  private boolean boundsAreSet = false;

/**
 * Show search dialogs
 */
 public void show() {

    if  (isLayoutInvalid) return;

    if ( !boundsAreSet ) {
      boundsAreSet = true;

      int width, height;
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      if ( bounds != null ){
         width = bounds.width;
         height = bounds.height;
      } else {
         width = 570;
         height = 120;
      }
      setBounds( ( screenSize.width - width ) / 2, 50, width, height );

      this.setResizable( false );
    }

    super.show();
    requestFocus();
  }

//---------------- START ActionListener implementation -------------
	public void actionPerformed( ActionEvent e ) {


    Object o = e.getSource();

    String sName = ( ( Component )o ).getName();

		if ( sName.equalsIgnoreCase( BTN_OK ) ) {
         search();
         setVisible( false );
    }else if ( sName.equalsIgnoreCase( BTN_SEL) ) {
     select();
	}else if ( sName.equalsIgnoreCase( BTN_CANCEL ) ) {
         setVisible( false );
    } else if ( sName.equalsIgnoreCase(invoke_button_name)) {
         show();
    }
	}
//------------------ END ActionListener implementation -------------

//------------------ START CarteHostListener implementation --------
  public void setParameters( CarteHost host, XmlElement layout ) {

      queryString = XmlUtils.getString( SEARCH_QUERY_STRING, layout, null );
      searchLayer = XmlUtils.getString( SEARCH_LAYER_STRING, layout, null );

      invoke_button_name = XmlUtils.getString( XmlConst.C_BUTTON, layout, null );

      map = host.getMapByName( layout );
      if ( map == null) return;

      map.statusListeners.addElement( this );

      this.host = host;

/*
      if (Strings.isNullOrBlank(queryString)) {
        layoutErrorMessage(SEARCH_QUERY_STRING);
			}

      if (Strings.isNullOrBlank(searchLayer)) {
        layoutErrorMessage(SEARCH_LAYER_STRING);
      }
*/
  }//setParameters


  public void stop() {
    this.setVisible( false );
    this.dispose();
	}
//------------------ END CarteHostListener implementation ----------

 private void layoutErrorMessage(String name){
        map.proxy.addStatusInfo( Const._ERR_LAYOUT,
          null, "FrameSearch " + getName() +
          ". The mandatory attribute " + name +
          " is not defined" );
        map.broadcastMessage( -1, null );
        isLayoutInvalid = true;
 }


//------------------ START StatusListener implementation -----------
  public void notifyStatus( int code, Object obj ) {}

  public void afterProjectLoaded( boolean bSuccess ) {

		setVisible( false );
    if ( bSuccess ) {
      this.setTitle(map.getResource("Search Data"));
      //set action listeners
      MapUtils.addActionListener( this, this, BTN_OK );
      MapUtils.addActionListener( this, this, BTN_CANCEL );

      MapUtils.addActionListener( this, (Container)host, invoke_button_name );

			wind_handler = new WindowEventHandler();
			this.addWindowListener( wind_handler );
    }
	}
//------------------ END StatusListener implementation -------------

/**
 * Window event handler
 */
  class WindowEventHandler extends WindowAdapter {
    private void closeWindow(){
      setVisible( false );
    }

    public void windowClosing( WindowEvent evt ) {
      closeWindow();
    }
  }

} //FrameSearch


