/*
 * Created on 2006/12/02
 *
 *
 * Copyright(c) 2006 Yoshimasa Matsumoto
 */
package netwatcher.networkcamera.gui.editor;

import java.sql.SQLException;
import java.util.logging.Logger;

import netjfwatcher.database.access.model.DBTableNetworkCamera;
import netjfwatcher.engine.socket.info.NetworkCameraInfo;
import netjfwatcher.engine.socket.info.NodeInformation;
import netjfwatcher.engine.view.editorpart.common.AbstractEditorNodeView;
import netjfwatcher.engine.view.editorpart.common.EditorInputNodeView;
import netjfwatcher.webbrowser.model.UrlEditorInput;
import netjfwatcher.webbrowser.view.BrowserEditors;
import netjfwatcher.webbrowser.view.BrowserEditorsManager;

import org.eclipse.jface.action.SubStatusLineManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

public class EditorNetworkCameraView extends AbstractEditorNodeView {
	/** ViewタイトルSuffix */
	public static final String TITLE_SUFFIX = " Camera View";

	private static final int COUNT_TEXT_WIDTH1 = 120;

	private static final int TEXT_WIDTH1 = 200;

	private static final int WIDTH_TEXT_WIDTH1 = 600;

	/* Scroll Compositeサイズ */
	private static final int[] SCROLL_COMPOSITE_SIZE = { 800, 800 };

	/* Horizontal Span 4 */
	private static final int HORIZONTAL_SPAN4 = 4;

	/* Horizontal Span 6 */
	private static final int HORIZONTAL_SPAN6 = 6;

	protected static Color WHITE_COLOR = new Color(null, 255, 255, 255);

	private Color textBackColor;

	/* Display */
	private Display display;

	private Button startButton;

	private Button stopButton;

	private Button loadButton;
	
	private Text refreshPeriodText;

	private Text controlURLText;

	private Text imageURLText;

	private NodeInformation nodeInfo;

	private NetworkCameraInfo networkCameraInfo;

	private Label imageLabel;

	private EditorCameraTimerProcessor timerProcessor;

	private Button browserButton;

	/* Logging */
	private static Logger logger;

	public EditorNetworkCameraView() {
		logger = Logger.getLogger(this.getClass().getName());

		textBackColor = WHITE_COLOR;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed()
	 */
	public boolean isSaveAsAllowed() {
		return false;
	}

	/**
	 * Editorウィンドウを生成します。
	 * 
	 * @param parent
	 *            Composite
	 */
	public void createPartControl(Composite parent) {

		display = parent.getDisplay();

		/* 入力設定値からノード監視情報を取得 */
		EditorInputNodeView nodeViewEditorInput = (EditorInputNodeView) getEditorInput();
		nodeInfo = nodeViewEditorInput.getNodeInfo();

		/*
		 * Viewレイアウト
		 */
		ScrolledComposite scrollComposite = new ScrolledComposite(parent,
				SWT.H_SCROLL | SWT.V_SCROLL);

		GridLayout layout = new GridLayout(1, false);
		scrollComposite.setLayout(layout);



		GridLayout gridLayout0 = new GridLayout(1, true);
		Composite composite0 = new Composite(scrollComposite, SWT.NONE);
		composite0.setLayout(gridLayout0);
		composite0.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL
				| GridData.VERTICAL_ALIGN_FILL));

		GridLayout gridLayoutURL = new GridLayout(3, false);
		Composite compositeURL = new Composite(composite0, SWT.NULL);
		compositeURL.setLayout(gridLayoutURL);
		compositeURL.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));


		GridLayout gridLayoutButton = new GridLayout(3, false);
		Composite compositeButton = new Composite(composite0, SWT.NULL);
		compositeButton.setLayout(gridLayoutButton);
		compositeButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));


		GridLayout gridLayoutJpeg = new GridLayout(1, false);
		Composite compositeJpeg = new Composite(composite0, SWT.NULL);
		compositeJpeg.setLayout(gridLayoutJpeg);
		compositeJpeg.setLayoutData(new GridData(GridData.BEGINNING));
		
		
		startButton = new Button(compositeButton, SWT.NULL);
		startButton.setText("Start");
		GridData gd = new GridData();
		gd.horizontalSpan = 1;
		startButton.setLayoutData(gd);

		stopButton = new Button(compositeButton, SWT.NULL);
		stopButton.setText("Stop");
		gd = new GridData();
		gd.horizontalSpan = 1;
		stopButton.setLayoutData(gd);

		
		loadButton = new Button(compositeButton, SWT.NULL);
		loadButton.setText("Load");
		gd = new GridData();
		gd.horizontalSpan = 1;
		loadButton.setLayoutData(gd);
		
		GridData gridData = null;
		Label label = new Label(compositeURL, SWT.NONE);
		label.setText("Refresh Period(sec)");
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		label.setLayoutData(gridData);
		refreshPeriodText = new Text(compositeURL, SWT.BORDER);
		refreshPeriodText.setBackground(textBackColor);
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		gridData.widthHint = COUNT_TEXT_WIDTH1;
		refreshPeriodText.setLayoutData(gridData);

		/* Dummy column */
		label = new Label(compositeURL, SWT.NONE);
		label.setText("");
		GridData gridData3 = new GridData();
		gridData3.horizontalSpan = 1;
		gridData3.verticalSpan = 1;
		label.setLayoutData(gridData3);

		label = new Label(compositeURL, SWT.NONE);
		label.setText("Control URL");
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		label.setLayoutData(gridData);

		controlURLText = new Text(compositeURL, SWT.BORDER | SWT.READ_ONLY);
		controlURLText.setBackground(textBackColor);
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		gridData.widthHint = WIDTH_TEXT_WIDTH1;
		controlURLText.setLayoutData(gridData);

		/* Button */
		browserButton = new Button(compositeURL, SWT.NONE);
		browserButton.setText("Browser start");

		label = new Label(compositeURL, SWT.NONE);
		label.setText("Image URL");
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		label.setLayoutData(gridData);
		imageURLText = new Text(compositeURL, SWT.BORDER | SWT.READ_ONLY);
		imageURLText.setBackground(textBackColor);
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		gridData.widthHint = WIDTH_TEXT_WIDTH1;
		imageURLText.setLayoutData(gridData);

		/* Dummy column */
		label = new Label(compositeURL, SWT.NONE);
		label.setText("");
		gridData3 = new GridData();
		gridData3.horizontalSpan = 1;
		gridData3.verticalSpan = 1;
		label.setLayoutData(gridData3);


		imageLabel = new Label(compositeJpeg, SWT.CENTER);

		gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = HORIZONTAL_SPAN6;
		// gridData.verticalSpan = 7;
		gridData.widthHint = 800;
		gridData.heightHint = 600;

		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;

		imageLabel.setLayoutData(gridData);

		scrollComposite.setContent(composite0);
		scrollComposite.setMinSize(SCROLL_COMPOSITE_SIZE[0],
				SCROLL_COMPOSITE_SIZE[1]);
		scrollComposite.setExpandHorizontal(true);
		scrollComposite.setExpandVertical(true);

		setSelectionListener();
		setText();
	}

	private void setSelectionListener() {
		startButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {

				startButton.setEnabled(false);
				startTimer();
				stopButton.setEnabled(true);

			}
		});
		stopButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				stopButton.setEnabled(false);
				stopTimer();
				startButton.setEnabled(true);
			}
		});
		loadButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				
				loadButton.setEnabled(false);
				setText();
				loadButton.setEnabled(true);


			}
		});
		
		browserButton.addSelectionListener(new SelectionListener() {
			public void widgetSelected(SelectionEvent event) {
				browserButton.setEnabled(false);
				if (!controlURLText.getText().equals("")) {
					setBrowserButton();
				}
				browserButton.setEnabled(true);
			}

			public void widgetDefaultSelected(SelectionEvent event) {
			}
		});

	}

	private void setText() {

		NetworkCameraInfo networkCameraInfo = loadNetworkCameraInfo();

		if (networkCameraInfo != null
				&& networkCameraInfo.getIpaddress() != null
				&& !networkCameraInfo.getIpaddress().equals("")) {

			refreshPeriodText.setText(networkCameraInfo.getRefreshPeriod());
			controlURLText.setText(networkCameraInfo.getControlURL());
			imageURLText.setText(networkCameraInfo.getJpegURL());
		} else {

			refreshPeriodText.setText("");
			controlURLText.setText("");
			imageURLText.setText("");
		}

	}

	private NetworkCameraInfo loadNetworkCameraInfo() {
		if (nodeInfo == null) {
			Shell shell = new Shell();
			MessageDialog.openError(shell, "Abort",
					"Abort Node information get");
			shell.dispose();
			return null;
		}
		networkCameraInfo = null;
		try {
			networkCameraInfo = DBTableNetworkCamera.getInstance().findCamera(
					nodeInfo.getIpaddress());

		} catch (SQLException e1) {
			Shell shell = new Shell();
			MessageDialog.openError(shell, "Abort Node information get", e1
					.getMessage());
			logger.warning("Abort Node information get" + e1.getMessage());
			shell.dispose();
		} catch (Exception e1) {
			Shell shell = new Shell();
			MessageDialog.openError(shell, "Abort Node information get", e1
					.getMessage());
			logger.warning("Abort Node information get" + e1.getMessage());
			shell.dispose();
		}
		return networkCameraInfo;
	}

	private void startTimer() {
		if (nodeInfo == null) {
			Shell shell = new Shell();
			MessageDialog.openError(shell, "Abort",
					"Abort Node information get");
			shell.dispose();
			return;
		}
		if (networkCameraInfo == null) {
			Shell shell = new Shell();
			MessageDialog.openError(shell, "Error",
					"Not found Network Camera Config.");
			shell.dispose();
			return;
		}

		String refreshPeriodString = refreshPeriodText.getText();

		int refreshPeriod = 3000;
		try {
			refreshPeriod = Integer.parseInt(refreshPeriodString);
		} catch (NumberFormatException e) {
			Shell shell = new Shell();
			MessageDialog.openError(shell, "Error", "Input error "
					+ e.getMessage());
			shell.dispose();
			refreshPeriodText.setFocus();
			return;
		}

		String targetURL = networkCameraInfo.getJpegURL();
		EditorCameraTimerProcessor.getInstance().setDisplay(display,
				getEditorSite(), imageLabel);
		EditorCameraTimerProcessor.getInstance().setTargetURL(
				nodeInfo.getIpaddress(), targetURL, refreshPeriod * 1000,
				networkCameraInfo.getUserName(),
				networkCameraInfo.getPassword());
		timerProcessor = EditorCameraTimerProcessor.getInstance();
		display.timerExec(EditorCameraTimerProcessor.TIMER, timerProcessor);
	}

	private void stopTimer() {
		timerProcessor = EditorCameraTimerProcessor.getInstance();
		display
				.timerExec(EditorCameraTimerProcessor.TIMER_STOP,
						timerProcessor);
	}

	private void setBrowserButton() {

		final String accessURL = controlURLText.getText();
		final IWorkbenchPage activePage;
		activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
				.getActivePage();
		BusyIndicator.showWhile(PlatformUI.getWorkbench().getDisplay(),
				new Runnable() {
					public void run() {
						try {
							IEditorPart editorPart = activePage.openEditor(
									new UrlEditorInput(accessURL, accessURL),
									BrowserEditors.class.getName());

							BrowserEditorsManager.getInstance()
									.setBrowserEditors(accessURL, editorPart);
						} catch (PartInitException e) {
							logger.warning("Browser open error : "
									+ e.getMessage());
							e.printStackTrace();
						}
					}
				});
	}

	/**
	 * ステータスライン表示をセットします。
	 */
	protected void setStatusLine() {
		/* ステータスライン表示有効化 */
		statusLineManager = (SubStatusLineManager) (getEditorSite()
				.getActionBars().getStatusLineManager());
		statusLineManager.setVisible(true);
	}

}
