package edu.fichte.pbi.ide.editors;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;

import edu.fichte.pbi.ide.commonsstolen.FileUtils;

public class ConfigEditor extends EditorPart {

	public static final String ID = "edu.fichte.pbi.ide.cfgeditor";
	public Text text;
	private IEditorInput input;
	private boolean dirty = false;
	private FileSystemFileEditorInput fileInput;
	public static boolean hasChanged = false;

	@Override
	public void doSave(IProgressMonitor monitor) {
		String content = text.getText();
		File file = fileInput.getFile();
		try {
			FileOutputStream out = new FileOutputStream(file);
			out.write(content.getBytes());
			out.close();
			beClean();
			hasChanged = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}



	@Override
	public boolean isSaveOnCloseNeeded() {
		return true;
	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		this.input = input;
		setSite(site);
		setInput(input);
		setTitle(input.getName());
	}

	private void beDirty() {
		dirty = true;
		firePropertyChange(PROP_DIRTY);
	}

	private void beClean() {
		dirty = false;
		firePropertyChange(PROP_DIRTY);
	}

	@Override
	public boolean isDirty() {
		return dirty;
	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}

	@Override
	protected void setInput(IEditorInput input) {
		super.setInput(input);
		this.input = input;
		this.fileInput = (FileSystemFileEditorInput) input;
	}

	@Override
	public void createPartControl(Composite parent) {
		parent = new Composite(parent, 0);
		parent.setLayout(new FillLayout());

		text = new Text(parent, SWT.MULTI | SWT.V_SCROLL);
		readFileContentToEditor();
		text.addModifyListener(new ModifyListener() {

			@Override
			public void modifyText(ModifyEvent e) {
				beDirty();
			}
		});
	}

	private void readFileContentToEditor() {
		if (input instanceof FileSystemFileEditorInput) {
			fileInput = (FileSystemFileEditorInput) input;
			File file = fileInput.getFile();
			try {
				text.setText(FileUtils.readFileToString(file));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void setFocus() {
		text.setFocus();
	}

	public File getFile() {
		return fileInput.getFile();
	}



	@Override
	public void doSaveAs() {
		// TODO Auto-generated method stub
		
	}

}