/*******************************************************************************
 * Copyright (c) 2000, 2004 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.team.examples.filesystem.subscriber;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.synchronize.SyncInfo;
import org.eclipse.team.core.variants.IResourceVariant;
import org.eclipse.team.core.variants.ThreeWayRemoteTree;
import org.eclipse.team.core.variants.ThreeWaySubscriber;
import org.eclipse.team.core.variants.ThreeWaySynchronizer;
import org.eclipse.team.examples.filesystem.FileSystemProvider;
import org.eclipse.team.examples.filesystem.StreamUtil;

import it.mice.voila2.sync.plugin.Activator;
import it.micegroup.voila2.cartridge.library.javaservice.FileCopyUtils;

/**
 * This is an example file system subscriber that overrides
 * ThreeWaySubscriber. It uses a repository
 * provider (<code>FileSystemProvider</code>) to determine and
 * manage the roots and to create resource variants. It also makes
 * use of a file system specific remote tree (<code>FileSystemRemoteTree</code>)
 * for provided the remote tree access and refresh.
 * 
 * @see ThreeWaySubscriber
 * @see ThreeWaySynchronizer
 * @see FileSystemProvider
 * @see FileSystemRemoteTree
 */
public class FileSystemSubscriber extends ThreeWaySubscriber {

	private static FileSystemSubscriber instance;
	
	/**
	 * Return the file system subscriber singleton.
	 * @return the file system subscriber singleton.
	 */
	public static synchronized FileSystemSubscriber getInstance() {
		if (instance == null) {
			instance = new FileSystemSubscriber();
		}
		return instance;
	}
	
	/**
	 * Create the file system subscriber.
	 */
	private FileSystemSubscriber() {
		//super(new ThreeWaySynchronizer(new QualifiedName(FileSystemPlugin.ID, "workpsace-sync"))); //$NON-NLS-1$
		super(new FileSystemThreeWaySynchronizer(new QualifiedName(Activator.PLUGIN_ID, "workpsace-sync"))); //$NON-NLS-1$
	}

	/* (non-Javadoc)
	 * @see org.eclipse.team.core.variants.ThreeWaySubscriber#getResourceVariant(org.eclipse.core.resources.IResource, byte[])
	 */
	public IResourceVariant getRemoteResourceVariant(IResource resource, byte[] bytes) throws TeamException {
		//RepositoryProvider provider = RepositoryProvider.getProvider(resource.getProject(), FileSystemPlugin.PROVIDER_ID);
		RepositoryProvider provider = FileSystemProvider.getFakeProvider(resource.getProject(), Activator.PROVIDER_ID);
		if (provider != null) {
			return ((FileSystemProvider)provider).getResourceVariant(resource, bytes);
		}
		return null;
	}

	public IResourceVariant getResourceVariant(IResource resource, byte[] bytes) throws TeamException {
		//RepositoryProvider provider = RepositoryProvider.getProvider(resource.getProject(), FileSystemPlugin.PROVIDER_ID);
		RepositoryProvider provider = FileSystemProvider.getFakeProvider(resource.getProject(), Activator.PROVIDER_ID);
		if (provider != null) {
			return ((FileSystemProvider)provider).getBaseResourceVariant(resource, bytes);
		}
		return null;
	}

	public IResourceVariant getResourceVariant(IResource resource) throws TeamException {
		//RepositoryProvider provider = RepositoryProvider.getProvider(resource.getProject(), FileSystemPlugin.PROVIDER_ID);
		RepositoryProvider provider = FileSystemProvider.getFakeProvider(resource.getProject(), Activator.PROVIDER_ID);
		if (provider != null) {
			return ((FileSystemProvider)provider).getBaseResourceVariant(resource);
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.team.core.variants.ThreeWaySubscriber#createRemoteTree()
	 */
	protected ThreeWayRemoteTree createRemoteTree() {
		return new FileSystemRemoteTree(this);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.team.core.subscribers.Subscriber#getName()
	 */
	public String getName() {
		return "File System Example"; //$NON-NLS-1$
	}

	/* (non-Javadoc)
	 * @see org.eclipse.team.core.subscribers.Subscriber#roots()
	 */
	public IResource[] roots() {
		List result = new ArrayList();
		IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
		for (int i = 0; i < projects.length; i++) {
			IProject project = projects[i];
			if(project.isAccessible()) {
				//RepositoryProvider provider = RepositoryProvider.getProvider(project, FileSystemPlugin.PROVIDER_ID);
				RepositoryProvider provider = FileSystemProvider.getFakeProvider(project, Activator.PROVIDER_ID);
				if(provider != null) {
					result.add(project);
				}
			}
		}
		return (IProject[]) result.toArray(new IProject[result.size()]);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.team.core.variants.ThreeWaySubscriber#handleRootChanged(org.eclipse.core.resources.IResource, boolean)
	 */
	public void handleRootChanged(IResource resource, boolean added) {
		// Override to allow FileSystemProvider to signal the addition and removal of roots
		super.handleRootChanged(resource, added);
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.team.core.variants.ResourceVariantTreeSubscriber#getSyncInfo(org.eclipse.core.resources.IResource, org.eclipse.team.core.variants.IResourceVariant, org.eclipse.team.core.variants.IResourceVariant)
	 */
	protected SyncInfo getSyncInfo(IResource local, IResourceVariant base, IResourceVariant remote) throws TeamException {
		// Override to use a custom sync info
		FileSystemSyncInfo info = new FileSystemSyncInfo(local, base, remote, this.getResourceComparator());
		info.init();
		return info;
	}

	/**
	 * Make the resource in-sync.
	 * @param resource the resource
	 * @throws TeamException
	 */
	public void makeInSync(IResource resource) throws TeamException {
		ThreeWaySynchronizer synchronizer = getSynchronizer();
		byte[] remoteBytes = synchronizer.getRemoteBytes(resource);
		if (remoteBytes == null) {
			if (resource.getType() == IResource.FOLDER) {
				try {
					if (((IFolder)resource).members().length == 0) {
						resource.delete(false, null);
					}
				} catch (CoreException e) {
					throw TeamException.asTeamException(e);
				}
			}
			if (!FileCopyUtils.exists(resource)) {
				FileSystemResourceVariant base = (FileSystemResourceVariant)getResourceVariant(resource);
				if (base != null) {
					if (resource.getType() == IResource.FOLDER) {
						StreamUtil.deleteDir(base.getFile());
					} else {
						base.getFile().delete();
					}
				}
				synchronizer.flush(resource, IResource.DEPTH_ZERO);
				checkOrphanFolder(synchronizer, resource);
			}
		} else {
			FileSystemResourceVariant remote = (FileSystemResourceVariant)getRemoteResourceVariant(resource, remoteBytes);
			//FileSystemResourceVariant base = (FileSystemResourceVariant)getResourceVariant(resource);
			try {
				FileSystemProvider provider = (FileSystemProvider)FileSystemProvider.getFakeProvider(resource.getProject(), Activator.PROVIDER_ID);
				if (resource.getType() == IResource.FOLDER) {
					StreamUtil.copyFolder(remote.getFile(), provider.getBaseFile(resource));
				} else {
					StreamUtil.copyFile(remote.getFile(), provider.getBaseFile(resource));
				}
				synchronizer.setBaseBytes(resource, remoteBytes);
			} catch (CoreException e) {
				throw TeamException.asTeamException(e);
			}
		}
	}

	private void checkOrphanFolder(ThreeWaySynchronizer synchronizer, IResource resource) throws TeamException {
		try {
			IContainer parentFolder = resource.getParent(); 
			pruneEmptyFolder(synchronizer, parentFolder);
			if (!FileCopyUtils.exists(parentFolder)) {
				checkOrphanFolder(synchronizer, parentFolder);
			}
		} catch (CoreException e) {
			throw TeamException.asTeamException(e);
		}
	}

	private void pruneEmptyFolder(ThreeWaySynchronizer synchronizer, IContainer parentFolder) throws CoreException {
		IResource[] children = parentFolder.members(true);
		for (int i = 0; i < children.length; i++) {
			if (children[i].getType() == IResource.FOLDER) {
				pruneEmptyFolder(synchronizer, (IFolder)children[i]);
			}
		}
		if (children.length == 0) {
			parentFolder.delete(true, null);
			FileSystemResourceVariant base = (FileSystemResourceVariant)getResourceVariant(parentFolder);
			if (base != null) {
				StreamUtil.deleteDir(base.getFile());
			}
			synchronizer.flush(parentFolder, IResource.DEPTH_ZERO);
		}
	}

	/**
	 * Make the change an outgoing change
	 * @param resource
	 * @throws TeamException 
	 */
	public void markAsMerged(IResource resource, IProgressMonitor monitor) throws TeamException {
		makeInSync(resource);
		try {
			if (FileCopyUtils.exists(resource)) {
				resource.touch(monitor);
			}
		} catch (CoreException e) {
			throw TeamException.asTeamException(e);
		}
	}

	public SyncInfo getSyncInfo(IResource resource) throws TeamException {
		if (!isSupervised(resource)) return null;
		IResourceVariant remoteResource = getRemoteTree().getResourceVariant(resource);
		IResourceVariant baseResource;
		if (getResourceComparator().isThreeWay()) {
			baseResource= getBaseTree().getResourceVariant(resource);
		} else {
			baseResource = null;
		}
		return getSyncInfo(resource, baseResource, remoteResource);
	}

	public boolean isSupervised(IResource resource) throws TeamException {
		if(resource.getType() == IResource.FOLDER && resource.getName().equals(".mddSyncFolder")) {
			return false;
		}	
		return super.isSupervised(resource);
	}

}
