package com.dskj.daikuan.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import com.dskj.daikuan.InitApp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

public class FileUtils {
    public static String APP_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "bkwatermark" + File.separator;
    public static String THUMBNAIL_DIR = APP_DIR + ".thumbnailrecord" + File.separator;
    public static String TEMP_DIR = APP_DIR + "temprecord" + File.separator;
    //以下三个不能清理
    public static String IMAGE_DIR = APP_DIR + "tempimage" + File.separator;
    public static String VIDEO_DIR = APP_DIR + "recordvideo" + File.separator;
    public static String THUMB_DIR = APP_DIR + ".videothumb" + File.separator;
    public static String CAPTURER_DIR = APP_DIR + "recordscreen" + File.separator;
    //以上三个不能清理
    //以下的 结尾的两个mp4文件和ts文件不能清理
    public static String VIDEO_DIR_HIDE = APP_DIR + ".recordvideo" + File.separator;

    /**
     *  从assets目录中复制整个文件夹内容到新的路径下
     *  @param  context  Context 使用CopyFiles类的Activity
     *  @param  oldPath  String  原文件路径  如：Data(assets文件夹下文件夹名称)
     *  @param  newPath  String  复制后路径  如：data/data/（手机内部存储路径名称）
     */
    public void copyFilesFromAssets(Context context,String oldPath,String newPath) {
        try {
                InputStream is = context.getAssets().open(oldPath);
                FileOutputStream fos = new FileOutputStream(new File(newPath));
                byte[] buffer = new byte[1024];
                int byteCount=0;
                while((byteCount=is.read(buffer))!=-1) {//循环从输入流读取 buffer字节
                    fos.write(buffer, 0, byteCount);//将读取的输入流写入到输出流
                }
                fos.flush();//刷新缓冲区
                is.close();
                fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    public static Uri getVideoContentUri(Context context, String path) {
        Uri uri = null;
        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Video.Media._ID}, MediaStore.Video.Media.DATA + "=? ",
                new String[]{path}, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/video/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }

            cursor.close();
        }

        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Video.Media.DATA, path);
            uri = context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
        }

        return uri;
    }


    public static long getAvilableSize(){
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.toString());
        long blocksize = stat.getBlockSizeLong();
        long availbleblocks = stat.getAvailableBlocksLong();
        long avilableSize = availbleblocks * blocksize;
        return avilableSize;
    }

    public static long getDirectorySize(File directory) {
        final File[] files = directory.listFiles();
        long size = 0;

        if (files == null) {
            return 0L;
        }

        for (final File file : files) {
            try {
                if (!isSymlink(file)) {
                    size += sizeOf(file);
                    if (size < 0) {
                        break;
                    }
                }
            } catch (IOException ioe) {
                // ignore exception when asking for symlink
            }
        }

        return size;
    }
    /**
     * 检测文件是否可用
     */
    public static boolean checkFile(String path) {
        if (!TextUtils.isEmpty(path)) {
            File f = new File(path);
            if (f != null && f.exists() && f.canRead() && (f.isDirectory() || (f.isFile()
                    && f.length() > 0))) {
                return true;
            }
        }
        return false;
    }

    public static String getExtension(String name) {
        String ext;

        if (name.lastIndexOf(".") == -1) {
            ext = "";

        } else {
            int index = name.lastIndexOf(".");
            ext = name.substring(index + 1, name.length());
        }
        return ext;
    }

    private static boolean isSymlink(File file) throws IOException {
        File fileInCanonicalDir;

        if (file.getParent() == null) {
            fileInCanonicalDir = file;
        } else {
            File canonicalDir = file.getParentFile().getCanonicalFile();
            fileInCanonicalDir = new File(canonicalDir, file.getName());
        }

        return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());
    }



    public static String getFileName(String path) {
        String s[] = path.split("/");
        if (s.length != 0)
            return "/" + s[s.length - 1];
        return "/";
    }
    /**
     * Return the name of file.
     *
     * @param file The file.
     * @return the name of file
     */
    public static String getFileName(final File file) {
        if (file == null) return "";
        return getFileName(file.getAbsolutePath());
    }

    private static long sizeOf(File file) {
        if (file.isDirectory()) {
            return getDirectorySize(file);
        } else {
            return file.length();
        }
    }


    public static void writeTxtToFile(List<String> strcontent, String filePath, String fileName) {
        makeFilePath(filePath, fileName);
        String strFilePath = filePath + fileName;
        String strContent = "";

        for (int i = 0; i < strcontent.size(); ++i) {
            strContent = strContent + "file " + strcontent.get(i) + "\r\n";
        }

        try {
            File file = new File(strFilePath);
            if (file.isFile() && file.exists()) {
                file.delete();
            }

            file.getParentFile().mkdirs();
            file.createNewFile();
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static boolean saveBitmap(Bitmap src, String dest) {
        if (src == null || TextUtils.isEmpty(dest)) {
            return false;
        }
        File destDir = new File(dest).getParentFile();
        if (destDir == null) {
            return false;
        }
        if (!destDir.exists()) {
            destDir.mkdirs();
        }

        FileOutputStream fout = null;
        boolean success = false;
        try {
            fout = new FileOutputStream(dest);
            src.compress(Bitmap.CompressFormat.PNG, 100, fout);

            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    success = false;
                }
            }
            return success;
        }
    }

    public static boolean saveBitmapPic(Context context,Bitmap src, String dest,String fileName) {
        if (src == null || TextUtils.isEmpty(dest)) {
            return false;
        }
        File destDir = new File(dest).getParentFile();
        if (destDir == null) {
            return false;
        }
        if (!destDir.exists()) {
            destDir.mkdirs();
        }

        FileOutputStream fout = null;
        boolean success = false;
        try {
            fout = new FileOutputStream(dest);
            src.compress(Bitmap.CompressFormat.PNG, 100, fout);


            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    success = false;
                }
            }
            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        dest, fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return success;
        }
    }


    public static String saveBitmap2Gallery(String dest,String fileName, Bitmap bitmap) {
        File mPicDir = new File(dest);

        if (mPicDir == null) {
            return null;
        }
        if (!mPicDir.exists()) {
            mPicDir.mkdirs();
        }
        OutputStream out = null;
        String[] pathArray = null;
        String[] typeArray = null;
        String fialeN=null;
        try {
            // Android 10版本 创建文件夹不成功，这里没有过多去研究
            boolean isMk = mPicDir.mkdirs();
            Log.d("ImageUtils ", "isMk = " + isMk);
            File mPicFile = new File(mPicDir, fileName);
            String mPicPath = mPicFile.getAbsolutePath();
            Log.d("ImageUtils ", "mPicPath = " + mPicPath);
            pathArray = new String[]{mPicFile.getAbsolutePath()};
            typeArray = new String[]{"image/png"};
            ContentValues values = new ContentValues();
            ContentResolver resolver = InitApp.initApp.getContentResolver();
            values.put(MediaStore.Images.ImageColumns.DATA, mPicPath);
            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName);
            values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/png");
            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, System.currentTimeMillis() + "");
            // 插入相册
            Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if (uri != null) {
                out = resolver.openOutputStream(uri);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                Log.d("ImageUtils ", "compress");
            }
            fialeN=fileName;
        } catch (Exception e) {
            e.printStackTrace();
            fialeN=null;
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                    Log.d("ImageUtils", "finally close");
                    // 扫描刷新
                    MediaScannerConnection.scanFile(InitApp.initApp, pathArray, typeArray, (s, uri) -> Log.d("ImageUtils", "onScanCompleted  s->" + s));
                    return fialeN;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fialeN;
    }


    public static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);

        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return file;
    }

    public static void makeRootDirectory(String filePath) {
        File file = null;

        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }

    /**
     * 递归删除文件和文件夹
     *
     * @param file
     */
    public static void deleteFileRecursively(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                file.delete();
                return;
            }
            for (File f : childFile) {
                deleteFileRecursively(f);
            }
            file.delete();
        }
    }

    public static String md5(String content) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("NoSuchAlgorithmException", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UnsupportedEncodingException", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    public static String getSaveUpdateDirectory() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String rootDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "SuperRecord" + File.separator + "update" + File.separator;
            File file = new File(rootDir);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    return null;
                }
            }
            return rootDir;
        } else {
            return null;
        }
    }


    /**
     * check the usability of the external storage.
     *
     * @return enable -> true, disable->false
     */
    public static boolean isExternalStorageEnable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    /**
     * get the external storage file path
     *
     * @return the file path
     */
    public static String getExternalStoragePath() {
        return getExternalStorageDir().getAbsolutePath();
    }

    /**
     * get the external storage file
     *
     * @return the file
     */
    public static File getExternalStorageDir() {
        return Environment.getExternalStorageDirectory();
    }

    public static String handleSpaceFilePath(String path) {
        if (TextUtils.isEmpty(path) || !path.contains(" ")) {
            return path;
        }

        File origin = new File(path);
        String fileName = origin.getName();
        if (fileName.contains(" ")) {
            fileName = fileName.replaceAll(" ", "");
        }

        File targetDir = new File(TEMP_DIR);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }

        File after = new File(targetDir, fileName);
        copyFile(origin, after);
        return after.getAbsolutePath();
    }


    public static boolean copyFile(File src, File dest) {
        if (src == null || dest == null) {
            return false;
        }
        if (dest.exists()) {
            return true;
        }

        if (TextUtils.equals(src.getParent(), dest.getParent())) {
            return src.renameTo(dest);
        }

        try {
            dest.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileChannel srcChannel = null;
        FileChannel dstChannel = null;

        boolean result = false;
        try {
            srcChannel = new FileInputStream(src).getChannel();
            dstChannel = new FileOutputStream(dest).getChannel();
            srcChannel.transferTo(0, srcChannel.size(), dstChannel);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                srcChannel.close();
                dstChannel.close();
            } catch (Exception e) {
                e.printStackTrace();
                result = false;
            }
        }
        return result;
    }

    public static String getTempDirectory() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(TEMP_DIR);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    return null;
                }
            }
            return TEMP_DIR;
        } else {
            return null;
        }
    }

    public static String getSaveRecordDirectory() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(VIDEO_DIR);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    return null;
                }
            }
            return VIDEO_DIR;
        } else {
            return null;
        }
    }

    public static String getSaveRecordPicDirectory() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(THUMB_DIR);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    return null;
                }
            }
            return THUMB_DIR;
        } else {
            return null;
        }
    }


    public static String getSaveCacheDirectory() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String rootDir = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + "ScreenRecord"
                    + File.separator + "cache"
                    + File.separator + "frame" + File.separator;
            File file = new File(rootDir);
            if (file.exists()) {
                deleteDir(rootDir);
            }
            file.mkdirs();
            return rootDir;
        } else {
            return null;
        }
    }

    public static String getSaveCoverDirectory() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String rootDir = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + "ScreenRecord"
                    + File.separator + "cache"
                    + File.separator + "cover" + File.separator;
            File file = new File(rootDir);
            if (!file.exists()) {
                file.mkdirs();
            }
            return rootDir;
        } else {
            return null;
        }
    }

    public static String getSaveScreenDirectory() {
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(CAPTURER_DIR);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    return null;
                }
            }
            return CAPTURER_DIR;
//        } else {
//            return null;
//        }
    }

    public static void deleteDir(final String pPath) {
        File dir = new File(pPath);
        deleteDirWithFile(dir);
    }

    public static void deleteDirWithFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete();
            else if (file.isDirectory())
                deleteDirWithFile(file);
        }
        dir.delete();
    }

    public static boolean fileIsExist(String filePath) {
        if (TextUtils.isEmpty(filePath)) return false;

        File file = new File(filePath);
        return file.exists();
    }


    public static void deleteFile(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        File file = new File(path);
        Log.i("XHXDEBUG","XHXDEBUG清理删除文件："+path);
        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }

    public static boolean isExists(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }

        File file = new File(path);
        return file.exists();
    }


    public static Uri getImageContentUri(Context context, String filePath) {
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        Uri uri = null;

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }

            cursor.close();
        }

        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        }

        return uri;
    }

    //存储assets中的文件到本地
    public static void getAssetsPath(Context context) {
        String fileName = "ic_share_image.jpeg";
        File testFolder = new File(APP_DIR + "/share");
        if (testFolder.exists() && testFolder.isDirectory()) {
            Log.d("", "test folder already exists");
        } else if (!testFolder.exists()) {
            testFolder.mkdir();
        }
        File modelFile = new File(testFolder, fileName);
        if (!modelFile.exists()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream is = context.getAssets().open(fileName);
                        FileOutputStream fos = new FileOutputStream(modelFile);
                        byte[] buffer = new byte[8192];
                        int read;
                        try {
                            while ((read = is.read(buffer)) != -1) {
                                fos.write(buffer, 0, read);
                            }
                        } finally {
                            fos.flush();
                            fos.close();
                            is.close();
                        }
                    } catch (IOException e) {
                        Log.d("", "Can't copy test file onto SD card");
                    }
                }
            }).start();
        }
    }

    public static int saveImageToGalleryShare(Context mContext, Bitmap bmp, String fileName) {
        //生成路径
        String root = APP_DIR;
        String dirName = "tempimage";
        File appDir = new File(root, dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        //获取文件
        File file = new File(appDir, fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            //通知系统相册刷新
//            mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
//                    Uri.fromFile(new File(file.getPath()))));
            //通知更新相册
            mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));

            return 2;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }

    /**
     * Drawable转换成一个Bitmap
     *
     * @param drawable drawable对象
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }


    /**
     * oldPath 和 newPath必须是新旧文件的绝对路径
     */
    public static File renameFile(String oldPath, String newPath) {
        if (TextUtils.isEmpty(oldPath)) {
            return null;
        }

        if (TextUtils.isEmpty(newPath)) {
            return null;
        }
        File oldFile = new File(oldPath);
        File newFile = new File(newPath);
        boolean b = oldFile.renameTo(newFile);
        File file2 = new File(newPath);
        return file2;
    }

    /**
     * 删除单个文件
     *
     * @param filePath$Name 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 复制asset到片尾
     */
    public static boolean copyAssetsToDst(Context context, String srcPath) {
        File targetDir0 = new File(APP_DIR);
        if (!targetDir0.exists()) {
            targetDir0.mkdirs();
        }

        File targetDir = new File(VIDEO_DIR_HIDE);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }

        try {
            File outFile = new File(VIDEO_DIR_HIDE, srcPath);
            InputStream is = context.getAssets().open(srcPath);
            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**读取assets文件*/
    public static String getFromAssets(Context context,String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    /*
     * Java文件操作 获取文件扩展名
     *
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
}
