/*
 * Copyright (C) 2016 Reece H. Dunn
 *
 * 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 uk.co.reecedunn.intellij.plugin.core.tests.psi;

import com.intellij.lang.Language;
import com.intellij.lang.LanguageUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import org.apache.xmlbeans.impl.common.IOUtil;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

public class MockPsiManager extends com.intellij.mock.MockPsiManager {
    public MockPsiManager(@NotNull Project project) {
        super(project);
    }

    private String streamToString(InputStream stream) throws IOException {
        StringWriter writer = new StringWriter();
        IOUtil.copyCompletely(new InputStreamReader(stream), writer);
        return writer.toString();
    }

    @Override
    public PsiFile findFile(@NotNull VirtualFile file) {
        try {
            Language language = LanguageUtil.getLanguageForPsi(getProject(), file);
            if (language == null) {
                return null;
            }

            String content = streamToString(file.getInputStream());
            return PsiFileFactory.getInstance(getProject()).createFileFromText(file.getName(), language, content, true, false, false, file);
        } catch (IOException e) {
            return null;
        }
    }
}

@@ -17,16 +17,21 @@
 (C) 2016
+-2018
  Reece H
@@ -37,16 +37,16 @@
 H. Dunn%0A
-
  *%0A * Li
@@ -889,16 +889,45 @@
 actory;%0A
+import kotlin.text.Charsets;%0A
 import o
@@ -1023,27 +1023,17 @@
 java.io.
-IOException
+*
 ;%0Aimport
@@ -1042,85 +1042,27 @@
 ava.
-io.InputStream;%0Aimport java.io.InputStreamReader;%0Aimport java.io.StringWriter
+nio.charset.Charset
 ;%0A%0Ap
@@ -1268,16 +1268,33 @@
 m stream
+, Charset charset
 ) throws
@@ -1320,46 +1320,64 @@
     
-StringWriter writer = new StringWriter
+ByteArrayOutputStream writer = new ByteArrayOutputStream
 ();%0A
@@ -1410,37 +1410,14 @@
 ely(
-new InputStreamReader(
 stream
-)
 , wr
@@ -1442,24 +1442,48 @@
 urn 
-writer.toString(
+new String(writer.toByteArray(), charset
 );%0A 
@@ -1733,24 +1733,24 @@
          %7D%0A%0A
-
             
@@ -1802,16 +1802,35 @@
 Stream()
+, file.getCharset()
 );%0A     

Fix the MockPsiManager.findFile logic in the tests to correctly handle UTF-8 text.