/*
 * 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.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 EditorNetworkCameraConfigView extends AbstractEditorNodeView {
	/** ViewタイトルSuffix */
	public static final String TITLE_SUFFIX = " Camera Config";

	public static final String INITIAL_PERIOD = "3";

	public static final String INITIAL_CONTROL_URL = "http://192.168.0.253";

	public static final String INITIAL_JPEG_URL = "http://192.168.0.253/SnapshotJPEG?Resolution=640x480&Quality=Standard&Count=1";

	/** 日時データ表示テキスト幅 */
	public static final int DATE_TEXT_WIDTH = 250;

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

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

	private static final int COUNT_TEXT_WIDTH1 = 120;

	private static final int TEXT_WIDTH1 = 200;

	private static final int WIDTH_TEXT_WIDTH1 = 600;

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

	private Color textBackColor;

	private Text userNameText;

	private Text passwordText;

	private Text refreshPeriodText;

	private Text controlURLText;

	private Text imageURLText;

	private Button loadButton;

	private Button saveButton;

	private Button browserButton;

	private NodeInformation nodeInfo;

	/* Logging */
	private static Logger logger;

	public EditorNetworkCameraConfigView() {
		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) {

		/* 入力設定値からノード監視情報を取得 */
		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);

		GridData gridData = null;

		GridLayout gridLayoutBase = new GridLayout(1, true);
		Composite compositeBase = new Composite(scrollComposite, SWT.NONE);
		compositeBase.setLayout(gridLayoutBase);
		compositeBase
				.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

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

		GridLayout gridLayout = new GridLayout(2, false);
		Composite composite1 = new Composite(compositeBase, SWT.NULL);
		composite1.setLayout(gridLayout);
		composite1.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
		gridData = new GridData();

		GridLayout gridLayoutButton = new GridLayout(HORIZONTAL_SPAN6, true);
		Composite compositeButton = new Composite(compositeBase, SWT.NONE);
		compositeButton.setLayoutData(new GridData(
				GridData.HORIZONTAL_ALIGN_FILL));
		compositeButton.setLayout(gridLayoutButton);

		Label label = new Label(composite1, SWT.NONE);
		label.setText("User Name");
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		label.setLayoutData(gridData);
		userNameText = new Text(composite1, SWT.BORDER);
		userNameText.setBackground(textBackColor);
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		gridData.widthHint = TEXT_WIDTH1;
		userNameText.setLayoutData(gridData);

		label = new Label(composite1, SWT.NONE);
		label.setText("Password");
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		label.setLayoutData(gridData);
		passwordText = new Text(composite1, SWT.BORDER | SWT.PASSWORD);
		passwordText.setBackground(textBackColor);
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		gridData.widthHint = TEXT_WIDTH1;
		passwordText.setLayoutData(gridData);

		label = new Label(composite1, SWT.NONE);
		label.setText("Refresh Period(sec)");
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		label.setLayoutData(gridData);
		refreshPeriodText = new Text(composite1, SWT.BORDER);
		refreshPeriodText.setBackground(textBackColor);
		gridData = new GridData();
		gridData.horizontalSpan = 1;
		gridData.verticalSpan = 1;
		gridData.widthHint = COUNT_TEXT_WIDTH1;
		refreshPeriodText.setLayoutData(gridData);

		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);
		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);
		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("");
		GridData gridData2 = new GridData();
		gridData2.horizontalSpan = 1;
		gridData2.verticalSpan = 1;
		label.setLayoutData(gridData2);

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

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

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

		setSelectionListener();

		setText();
	}

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

				loadButton.setEnabled(false);
				setText();
				loadButton.setEnabled(true);

			}
		});
		saveButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				saveButton.setEnabled(false);
				saveNetworkCameraInfo();
				saveButton.setEnabled(true);
			}
		});

		browserButton.addSelectionListener(new SelectionListener() {
			public void widgetSelected(SelectionEvent event) {
				browserButton.setEnabled(false);
				setBrowserButton();
				browserButton.setEnabled(true);
			}

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

	}

	private void saveNetworkCameraInfo() {
		NetworkCameraInfo networkCameraInfo = new NetworkCameraInfo();
		networkCameraInfo.setIpaddress(nodeInfo.getIpaddress());
		networkCameraInfo.setUserName(userNameText.getText());
		networkCameraInfo.setPassword(passwordText.getText());
		networkCameraInfo.setRefreshPeriod(refreshPeriodText.getText());
		networkCameraInfo.setControlURL(controlURLText.getText());
		networkCameraInfo.setJpegURL(imageURLText.getText());
		try {
			NetworkCameraInfo workNetworkCameraInfo = loadNetworkCameraInfo();
			if (workNetworkCameraInfo != null) {
				DBTableNetworkCamera.getInstance().updateCamera(
						networkCameraInfo.getIpaddress(), networkCameraInfo);
			} else {
				DBTableNetworkCamera.getInstance().putCamera(
						networkCameraInfo.getIpaddress(), networkCameraInfo);
			}
		} 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();
		}
	}

	private void setText() {

		NetworkCameraInfo networkCameraInfo = loadNetworkCameraInfo();

		if (networkCameraInfo != null
				&& networkCameraInfo.getIpaddress() != null
				&& !networkCameraInfo.getIpaddress().equals("")) {
			userNameText.setText(networkCameraInfo.getUserName());
			passwordText.setText(networkCameraInfo.getPassword());
			refreshPeriodText.setText(networkCameraInfo.getRefreshPeriod());
			controlURLText.setText(networkCameraInfo.getControlURL());
			imageURLText.setText(networkCameraInfo.getJpegURL());
		} else {
			userNameText.setText("");
			passwordText.setText("");
			refreshPeriodText.setText(INITIAL_PERIOD);
			controlURLText.setText(INITIAL_CONTROL_URL);
			imageURLText.setText(INITIAL_JPEG_URL);
		}

	}

	private NetworkCameraInfo loadNetworkCameraInfo() {
		NetworkCameraInfo 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 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);
	}

}
