package com.github.helltar.anpaside;

import static com.github.helltar.anpaside.Consts.LANG_ERR_CREATE_DIR;
import static com.github.helltar.anpaside.Consts.LANG_ERR_FILE_NOT_FOUND;
import static com.github.helltar.anpaside.logging.Logger.LMT_ERROR;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;

import com.github.helltar.anpaside.logging.Logger;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class Utils {

    public static boolean mkdir(String dirName) {
        if (new File(dirName).mkdirs() | fileExists(dirName)) {
            return true;
        } else {
            Logger.addLog(LANG_ERR_CREATE_DIR + ": " + dirName, LMT_ERROR);
        }

        return false;
    }

    public static boolean copyFileToDir(String srcFile, String destDir) {
        return copyFileToDir(srcFile, destDir, true);
    }

    public static boolean copyFileToDir(String srcFile, String destDir, boolean showErrMsg) {
        if (fileExists(srcFile, showErrMsg)) {
            try {
                FileUtils.copyFileToDirectory(new File(srcFile), new File(destDir));
                return true;
            } catch (IOException ioe) {
                Logger.addLog(ioe);
            }
        }

        return false;
    }

    public static boolean fileExists(String filename) {
        return fileExists(filename, false);
    }

    public static boolean fileExists(String filename, boolean showErrMsg) {
        if (!filename.isEmpty()) {
            if (new File(filename).exists()) {
                return true;
            } else if (showErrMsg) {
                Logger.addLog(LANG_ERR_FILE_NOT_FOUND + ": " + filename, LMT_ERROR);
            }
        }

        return false;
    }

    public static String getFileNameOnly(String filename) {
        return FilenameUtils.getBaseName(filename);
    }

    public static long getFileSize(String filename) {
        return new File(filename).length() / 1024;
    }

    public static boolean createTextFile(String filename, String text) {
        try {
            FileUtils.writeStringToFile(new File(filename), text);
            return true;
        } catch (IOException ioe) {
            Logger.addLog(ioe);
        }

        return false;
    }

    public static ProcessResult runProc(String args) {
        boolean result = false;
        StringBuilder output = new StringBuilder();

        try {
            Process process = Runtime.getRuntime().exec(args);

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;

            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
                process.waitFor();
            }

            result = true;

        } catch (IOException | InterruptedException ioe) {
            Logger.addLog(ioe);
        }

        return new ProcessResult(result, output.toString());
    }

    public static String getPathFromUri(final Context context, final Uri uri) {
        if (DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return uri.toString();
    }

    private static String getDataColumn(Context context, Uri uri) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return uri.toString();
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
}

@@ -248,171 +248,8 @@
 R;%0A%0A
-import android.content.Context;%0Aimport android.database.Cursor;%0Aimport android.net.Uri;%0Aimport android.os.Environment;%0Aimport android.provider.DocumentsContract;%0A%0A
 impo
@@ -295,16 +295,16 @@
 Logger;%0A
+
 %0Aimport 
@@ -494,16 +494,49 @@
 mReader;
+%0Aimport java.nio.charset.Charset;
 %0A%0Apublic
@@ -2213,16 +2213,42 @@
 e), text
+, Charset.defaultCharset()
 );%0A     
@@ -3004,32 +3004,32 @@
 oe);%0A        %7D%0A%0A
+
         return n
@@ -3082,1598 +3082,7 @@
    %7D
-%0A%0A    public static String getPathFromUri(final Context context, final Uri uri) %7B%0A        if (DocumentsContract.isDocumentUri(context, uri)) %7B%0A            if (isExternalStorageDocument(uri)) %7B%0A                final String docId = DocumentsContract.getDocumentId(uri);%0A                final String%5B%5D split = docId.split(%22:%22);%0A                final String type = split%5B0%5D;%0A%0A                if (%22primary%22.equalsIgnoreCase(type)) %7B%0A                    return Environment.getExternalStorageDirectory() + %22/%22 + split%5B1%5D;%0A                %7D%0A            %7D%0A        %7D else if (%22content%22.equalsIgnoreCase(uri.getScheme())) %7B%0A            return getDataColumn(context, uri);%0A        %7D else if (%22file%22.equalsIgnoreCase(uri.getScheme())) %7B%0A            return uri.getPath();%0A        %7D%0A%0A        return uri.toString();%0A    %7D%0A%0A    private static String getDataColumn(Context context, Uri uri) %7B%0A        Cursor cursor = null;%0A        final String column = %22_data%22;%0A        final String%5B%5D projection = %7Bcolumn%7D;%0A%0A        try %7B%0A            cursor = context.getContentResolver().query(uri, projection, null, null, null);%0A%0A            if (cursor != null && cursor.moveToFirst()) %7B%0A                final int index = cursor.getColumnIndexOrThrow(column);%0A                return cursor.getString(index);%0A            %7D%0A        %7D finally %7B%0A            if (cursor != null) %7B%0A                cursor.close();%0A            %7D%0A        %7D%0A%0A        return uri.toString();%0A    %7D%0A%0A    private static boolean isExternalStorageDocument(Uri uri) %7B%0A        return %22com.android.externalstorage.documents%22.equals(uri.getAuthority());%0A    %7D
 %0A%7D%0A

del. not used methods