/*******************************************************************************
 * Copyright (c) 2020 Aston University.
 * 
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the Eclipse
 * Public License, v. 2.0 are satisfied: GNU General Public License, version 3.
 *
 * SPDX-License-Identifier: EPL-2.0 OR GPL-3.0
 *
 * Contributors:
 *     Antonio Garcia-Dominguez - initial API and implementation
 ******************************************************************************/
package org.eclipse.hawk.ui.jgit;

import java.io.File;

import org.eclipse.hawk.core.IVcsManager;
import org.eclipse.hawk.git.JGitRepository;
import org.eclipse.hawk.osgiserver.HModel;
import org.eclipse.hawk.ui2.dialog.HVCSDialog;
import org.eclipse.hawk.ui2.vcs.IVcsConfigurationBlock;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
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.DirectoryDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

public class JGitConfigurationBlock implements IVcsConfigurationBlock {

	private HVCSDialog dialog;

	private Text txtGitRepo;
	private Text txtBranch;
	private Button btnBrowse;

	@Override
	public boolean isApplicableTo(IVcsManager manager) {
		return manager instanceof JGitRepository;
	}

	@Override
	public void createBlock(Composite container, HVCSDialog dialog) {
		this.dialog = dialog;
		final JGitRepository managerToEdit = (JGitRepository) dialog.getManagerToEdit();

		final GridLayout containerLayout = new GridLayout();
		containerLayout.numColumns = 3;
		container.setLayout(containerLayout);

		// Location + browse
		final Label lblLocation = new Label(container, SWT.NONE);
		lblLocation.setText("Repository folder:");
		txtGitRepo = new Text(container, SWT.BORDER);
		final GridData txtVCSLocationLayoutData = new GridData(SWT.FILL, SWT.CENTER, true, false);
		txtVCSLocationLayoutData.widthHint = 300;
		txtGitRepo.setLayoutData(txtVCSLocationLayoutData);
		if (managerToEdit != null) {
			txtGitRepo.setText(managerToEdit.getLocation());
			txtGitRepo.setEnabled(false);
		}
		txtGitRepo.addModifyListener(e -> updateDialog());
		txtGitRepo.setToolTipText("Path to the root folder of the repository (only local repositories are supported)");

		btnBrowse = new Button(container, SWT.PUSH);
		GridData gridDataB = new GridData();
		btnBrowse.setLayoutData(gridDataB);
		btnBrowse.setText("Browse...");
		btnBrowse.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				DirectoryDialog dd = new DirectoryDialog(container.getShell(), SWT.OPEN);
				dd.setMessage("Select a Git repository root to add to the indexer");
				dd.setText("Select a directory");
				String result = dd.open();
				if (result != null) {
					txtGitRepo.setText(result);
				}
			}
		});
		btnBrowse.setEnabled(false);

		// Branch (optional)
		final Label lblBranch = new Label(container, SWT.NONE);
		lblBranch.setText("Branch (optional):");
		txtBranch = new Text(container, SWT.BORDER);
		final GridData txtBranchLayoutData = new GridData(SWT.FILL, SWT.CENTER, true, false);
		txtBranchLayoutData.horizontalSpan = 2;
		txtBranch.setLayoutData(txtBranchLayoutData);
		if (managerToEdit != null) {
			if (managerToEdit.getBranch() != null) {
				txtBranch.setText(managerToEdit.getBranch());
			}
			txtBranch.setEnabled(false);
		}
		txtBranch.addModifyListener(e -> updateDialog());
		txtBranch.setToolTipText("Branch to be checked out (current branch if empty)");

		updateDialog();
	}

	@Override
	public void okPressed(HModel hawkModel, boolean isFrozen) {
		final String vcsType = dialog.getSelectedVCSManager().getClass().getName();
		String location = txtGitRepo.getText();
		final String sBranch = txtBranch.getText().trim();
		if (sBranch.length() > 0) {
			location = String.format("%s?%s=%s",
				new File(location).toURI().toString(),
				JGitRepository.BRANCH_QPARAM,
				sBranch);
		}

		final IVcsManager managerToEdit = dialog.getManagerToEdit();
		if (managerToEdit == null) {
			hawkModel.addVCS(location, vcsType, null, null, isFrozen);
		} else {
			managerToEdit.setFrozen(isFrozen);
		}
	}

	private void updateDialog() {
		if (dialog.getManagerToEdit() == null) {
			final IVcsManager vcsManager = dialog.getSelectedVCSManager();
			btnBrowse.setEnabled(vcsManager != null && vcsManager.isPathLocationAccepted());
		}

		if (!isLocationValid()) {
			dialog.setErrorMessage("The location is not valid");
		} else if (dialog.getSelectedVCSManager() == null) {
			dialog.setErrorMessage("No VCS manager type has been selected");
		} else {
			dialog.setErrorMessage(null);
		}
	}

	private boolean isLocationValid() {
		final File f = new File(txtGitRepo.getText());
		return f.isDirectory() && f.exists();
	}

}
