package org.xtext.example.mydsl.ui.autoedit;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;
import org.eclipse.xtext.naming.QualifiedName;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.ui.editor.model.IXtextDocument;
import org.eclipse.xtext.ui.editor.model.XtextDocumentProvider;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import org.eclipse.xtext.ui.editor.model.XtextDocumentProvider;
import org.xtext.example.mydsl.myDsl.ContentModel;
import org.xtext.example.mydsl.myDsl.Web;
import org.xtext.example.mydsl.myDsl.util.SitePermission7;
import org.xtext.example.mydsl.myDsl.util.Sitepermissiontwo;
import org.xtext.example.mydsl.scoping.scopdeneme;
import org.xtext.example.mydsl.ui.util.XtextResourceUtil1;
import org.xtext.example.mydsl2.myDsl2.Group;
import org.xtext.example.mydsl2.myDsl2.MyDsl2Factory;
import org.xtext.example.mydsl2.myDsl2.MyDsl2Package;
import org.xtext.example.mydsl2.myDsl2.SitePermission;
import org.xtext.example.mydsl2.myDsl2.UserModel;
import org.xtext.example.mydsl2.myDsl2.util.Sitepermission6;
import org.xtext.example.mydsl2.myDsl2.util.UserConstant1;

import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;


public class AutoEdit extends XtextDocumentProvider{
	
	final static List<String> contentUnitNames = new ArrayList<String>();
	
	@Inject
	SitePermission7  sitepermission6;
	@Inject
	scopdeneme scop;
	
	@Override
	protected ISchedulingRule getSaveRule(Object element) {
	
	return null;
	}
	
	@Override
	protected void doSaveDocument(IProgressMonitor monitor, Object element,
			IDocument document, boolean overwrite) throws CoreException {
		super.doSaveDocument(monitor, element, document, overwrite);
		List<String> keywords = Arrays.asList("Web", "ContentModel");

		StringBuilder sb = new StringBuilder();
		for (String s : keywords) {
			sb.append(s);
			sb.append("|");
        }
		
		

		/*
		 * En sondaki | karakterini sil.
		 */
		String keywordsString = sb.deleteCharAt(sb.length() - 1).toString();
        
		String pattern = String.format("\\b(%s)\\b((\\w|\\s|\\.)+)[{]",
				keywordsString);

		Pattern compile = Pattern.compile(pattern);

		String alldocument = document.get();

		String alldocumentWithoutComment = XtextResourceUtil1
				.returnStringWithoutComments(alldocument);
		java.util.regex.Matcher matcher = compile
				.matcher(alldocumentWithoutComment);
		final List<String> contentUnitNames = new ArrayList<String>();
		while (matcher.find()) {
			String kelime = matcher.group(2).trim();
			contentUnitNames.add(kelime);

		}

		((IXtextDocument) document).
				modify(new IUnitOfWork<Void, XtextResource>() {

					@Override
					public java.lang.Void exec(XtextResource state)
							throws Exception {
						int index = 0;
						ContentModel mymodel = (ContentModel) state
								.getContents().get(0);
						// System.out.println(mymodel.getName());
						if (mymodel.getDisplayName() == null
								|| mymodel.getDisplayName().equals(""))
							mymodel.setDisplayName(contentUnitNames.get(index));
						mymodel.setName(contentUnitNames.get(index).trim()
								.replace(" ", ""));
						index++;
						

						Web rootWeb = mymodel.getOwnedWeb();
                       
						if (rootWeb.getDisplayName() == null
								|| rootWeb.getDisplayName().equals("")){
							rootWeb.setDisplayName(contentUnitNames.get(index));
						rootWeb.setName(contentUnitNames.get(index).trim()
								.replace(" ", ""));
						//System.out.println(rootWeb.getSitePermission().eContainer().eContents());
						//String um =rootWeb.getSitePermission().eContainer().toString();
                         String guid =rootWeb.getGuID();
                         SitePermission s=    sitepermission6.createDefaultSitePermission(contentUnitNames.get(index),guid);
                         sitepermission6.loadForCreateSitePermission(rootWeb, s);
                         //scop.getImplicitImports(true);
                         //System.out.println(scop.getImplicitImports(true));
                        String userfile = sitepermission6.getUserFileLocationURI();
                        // org.eclipse.xtext.resource.IResourceDescriptions.getResourceDescription(URI.createURI(userfile));
                          rootWeb.setSitePermission(s);
					      
					
						}
						index++;
						// System.out.println(index);

						
                       // Webleri dolas
						EList<Web> ownedwebs = rootWeb.getOwnedWeb();
						for (Iterator<Web> iterator6 = ownedwebs.iterator(); iterator6
								.hasNext();) {
							Web w = (Web) iterator6.next();
							index = setRecursivelyWebsDisplayName(w, index,
									contentUnitNames);
						}

						

						return null;

					}

				});

		super.doSaveDocument(monitor, element, document, overwrite);
	}

	public  int setRecursivelyWebsDisplayName(Web web, int index,
			List<String> contentUnitNames) {

		if (web.getDisplayName() == null || web.getDisplayName().equals("")){
			web.setDisplayName(contentUnitNames.get(index));
		web.setName(contentUnitNames.get(index).trim().replace(" ", ""));
		// System.out.println(web.getName());
		String guid =web.getGuID();
		
		 SitePermission s=   sitepermission6.createDefaultSitePermission(contentUnitNames.get(index),guid);
		    sitepermission6.loadForCreateSitePermission(web, s);
		    web.setSitePermission(s);
		
		
	   }
		index++;


		if (!web.getOwnedWeb().isEmpty()) {

			EList<Web> webs = web.getOwnedWeb();

			for (Iterator<Web> iterator = webs.iterator(); iterator.hasNext();) {
				Web w = (Web) iterator.next();
				// System.out.println(w);
				index = setRecursivelyWebsDisplayName(w, index,
						contentUnitNames);
			}

		}
		return index;
	}
	

}
