/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.api.internal.file;

import org.gradle.api.UncheckedIOException;
import org.gradle.api.file.FileSystemLocation;
import org.gradle.internal.exceptions.DiagnosticsVisitor;
import org.gradle.internal.nativeintegration.filesystem.FileSystem;
import org.gradle.internal.typeconversion.NotationConvertResult;
import org.gradle.internal.typeconversion.NotationConverter;
import org.gradle.internal.typeconversion.NotationParser;
import org.gradle.internal.typeconversion.NotationParserBuilder;
import org.gradle.internal.typeconversion.TypeConversionException;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileOrUriNotationConverter implements NotationConverter<Object, Object> {

    private static final Pattern URI_SCHEME = Pattern.compile("[a-zA-Z][a-zA-Z0-9+-\\.]*:.+");
    private static final Pattern ENCODED_URI = Pattern.compile("%([0-9a-fA-F]{2})");
    private final FileSystem fileSystem;

    public FileOrUriNotationConverter(FileSystem fileSystem) {
        this.fileSystem = fileSystem;
    }

    public static NotationParser<Object, Object> parser(FileSystem fileSystem) {
        return NotationParserBuilder
                .toType(Object.class)
                .typeDisplayName("a File or URI")
                .converter(new FileOrUriNotationConverter(fileSystem))
                .toComposite();
    }

    @Override
    public void describe(DiagnosticsVisitor visitor) {
        visitor.candidate("A String or CharSequence path").example("'src/main/java' or '/usr/include'");
        visitor.candidate("A String or CharSequence URI").example("'file:/usr/include'");
        visitor.candidate("A File instance.");
        visitor.candidate("A Path instance.");
        visitor.candidate("A Directory instance.");
        visitor.candidate("A RegularFile instance.");
        visitor.candidate("A URI or URL instance.");
    }

    public void convert(Object notation, NotationConvertResult<? super Object> result) throws TypeConversionException {
        if (notation instanceof File) {
            result.converted(notation);
            return;
        }
        if (notation instanceof Path) {
            result.converted(((Path)notation).toFile());
            return;
        }
        if (notation instanceof FileSystemLocation) {
            result.converted(((FileSystemLocation)notation).getAsFile());
            return;
        }
        if (notation instanceof URL) {
            try {
                notation = ((URL) notation).toURI();
            } catch (URISyntaxException e) {
                throw new UncheckedIOException(e);
            }
        }
        if (notation instanceof URI) {
            URI uri = (URI) notation;
            if ("file".equals(uri.getScheme()) && uri.getPath() != null) {
                result.converted(new File(uri.getPath()));
            } else {
                result.converted(uri);
            }
            return;
        }
        if (notation instanceof CharSequence) {
            String notationString = notation.toString();
            if (notationString.startsWith("file:")) {
                result.converted(new File(uriDecode(notationString.substring(5))));
                return;
            }
            for (File file : File.listRoots()) {
                String rootPath = file.getAbsolutePath();
                String normalisedStr = notationString;
                if (!fileSystem.isCaseSensitive()) {
                    rootPath = rootPath.toLowerCase();
                    normalisedStr = normalisedStr.toLowerCase();
                }
                if (normalisedStr.startsWith(rootPath) || normalisedStr.startsWith(rootPath.replace(File.separatorChar, '/'))) {
                    result.converted(new File(notationString));
                    return;
                }
            }
            // Check if string starts with a URI scheme
            if (URI_SCHEME.matcher(notationString).matches()) {
                try {
                    result.converted(new URI(notationString));
                    return;
                } catch (URISyntaxException e) {
                    throw new UncheckedIOException(e);
                }
            }
            result.converted(new File(notationString));
        }
    }

    private String uriDecode(String path) {
        StringBuffer builder = new StringBuffer();
        Matcher matcher = ENCODED_URI.matcher(path);
        while (matcher.find()) {
            String val = matcher.group(1);
            matcher.appendReplacement(builder, String.valueOf((char) (Integer.parseInt(val, 16))));
        }
        matcher.appendTail(builder);
        return builder.toString();
    }

}

@@ -3965,32 +3965,100 @@
 ;%0A            %7D%0A
+            if (URI_SCHEME.matcher(notationString).matches()) %7B%0A    
             for 
@@ -4102,24 +4102,28 @@
             
+ 
+   
 String rootP
@@ -4148,24 +4148,28 @@
 lutePath();%0A
+    
             
@@ -4223,24 +4223,28 @@
             
+    
 if (!fileSys
@@ -4288,16 +4288,20 @@
         
+  
+  
 rootPath
@@ -4319,32 +4319,36 @@
 .toLowerCase();%0A
+    
                 
@@ -4404,34 +4404,42 @@
                 
-%7D%0A
+    %7D%0A    
                 
@@ -4563,32 +4563,36 @@
                 
+    
 result.converted
@@ -4631,32 +4631,36 @@
                 
+    
 return;%0A        
@@ -4664,33 +4664,23 @@
         
-   %7D%0A
        
-     
 %7D%0A      
@@ -4689,115 +4689,13 @@
     
-// Check if string starts with a URI scheme%0A            if (URI_SCHEME.matcher(notationString).matches()) %7B
+    %7D
 %0A   

Make UriNotationConverter faster on Windows