/* $Id: ShowLocalViewAction.java 287 2011-08-03 13:10:08Z shayashi $ */
package smart_gs.swingui.toolbar.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.html.HTML;

import smart_gs.debugprint.Debugprint;
import smart_gs.logical.GSResource;
import smart_gs.logical.Region;
import smart_gs.logical.TextSegment;
import smart_gs.reasoning_web.logical.GS_RWRepository;
import smart_gs.smleditor.swingui.GSEditorTextPane;
import smart_gs.swingui.AbstractGSWindow;
import smart_gs.swingui.WorkspaceWindow;
import smart_gs.swingui.toolbar.GSEditorToolBar;
import sml_editor.swingui.EditorTextPane;

public class ShowLocalViewAction implements ActionListener {
	
	private AbstractGSWindow parent;
	private GSResource resource;
	public ShowLocalViewAction(AbstractGSWindow parent){
		this.parent = parent;
	}
	public ShowLocalViewAction(GSResource resource){
		this.resource = resource;
	}
	public void execute(){
		if(resource == null){
			return;
		}
		if(GS_RWRepository.getInstance().hasLink(resource)){
			GS_RWRepository.getInstance().showLocalView(resource);
		}		
	}
	
	public void actionPerformed(ActionEvent e) {
		List<Region> regions = this.parent.getSpread().getSelectedRegions();
		
		// カーソル位置から
		GSEditorToolBar gsEditorToolBar = WorkspaceWindow.getInstance().getGSEditorToolBar();
		if(gsEditorToolBar != null){
			if(gsEditorToolBar.getMode() == 0 || gsEditorToolBar.getMode() == 1){
				EditorTextPane textPane = gsEditorToolBar.getEditorTextPane();
				SimpleAttributeSet element = textPane.getSelectIDFromPos(textPane.getCaretPosition());
				if(element == null){
					return;
				}
				int id = -1;
				try{
					id = new Integer((String)element.getAttribute(HTML.Attribute.HREF)).intValue();
				}catch(NumberFormatException ex){}
				TextSegment segment = ((GSEditorTextPane)textPane).getSmartDocument().getSegmentByID(id);
				new ShowLocalViewAction(segment).execute();
			}
		}
		
		if(regions.size() == 0){
			// resourceを選択させる
			return;
		}
		 
		for(int i=0;i<regions.size();i++){
			if(GS_RWRepository.getInstance().hasLink(regions.get(i))){
				GS_RWRepository.getInstance().showLocalView(regions.get(i));
			}	
		}
	}
	
	
}
