package macampcorp.macamp.utils.files;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

import macampcorp.macamp.utils.L;

/**
 * Created by ptitcois on 27/03/17.
 */
public class FileManager {
    protected static AssetManager m_asset=null;
    protected static Activity m_act = null;

    public static void init(Activity a)
    {
        m_act=a;
        m_asset=a.getAssets();
    }

    private static boolean isInit()  {

        return true;
    }

    public static InputStream openFile(Context a, String path)  {
        isInit();
        InputStream is = null;
        try {
            is = a.getAssets().open(path);
        } catch (IOException e) {
        }
        return is;
    }
    private static final String[]  IMG_EXT={"", ".jpg" , ".JPG",
            ".jpeg" , ".JPEG",
            ".bmp", ".BMP",
            ".gif", ".GIF",
            ".png", ".PNG"
            };
    private static final String[]  MEDIA_EXT={"", ".3gp" , ".3GP",
            ".mp4", ".MP4",
            ".avi", ".AVI",
            ".webm", ".WEBM",
            ".mkv", ".MKV",
            ".aac", ".AAC",
            ".flac", ".FLAC",
            ".mid", ".MID",
            ".midi", ".MIDI",
            ".mp3", ".MP3",
            ".3gpp", ".3GPP",
            ".wav", ".WAV",
            ".ogg", ".OGG"};

    private static InputStream testIimage(Context a,String path)  {
        for(int i=0; i<IMG_EXT.length; i++)
        {
            InputStream is = openFile(a, path+IMG_EXT[i]);
            if(is!=null) {
                L.error("Image found at '"+(path+IMG_EXT[i])+"'");
                return is;
            }
        }
        throw  new RuntimeException("Image '"+path+"' non trouvé (en cherchant les extensions");
    }

    public static Bitmap openImage(Context a,String path)  {
        isInit();
        InputStream is = null;
        Bitmap bitmap = null;
        is = testIimage(a, path);
        if(is==null) return null;
        bitmap = BitmapFactory.decodeStream(is);

        return bitmap;
    }

    public static Uri getUri(Context a, String path) throws Exception {
        isInit();
        return Uri.parse("file:///android_asset/" + path);
    }


    private static AssetFileDescriptor testVideo(Context a,String path) {
        for(int i=0; i<MEDIA_EXT.length; i++)
        {
            AssetFileDescriptor is = null;
            try {
                is = a.getAssets().openFd(path+MEDIA_EXT[i]);

                if(is!=null)
                    return is;
            } catch (IOException e) {
            }
        }
        return null;
    }

    public static AssetFileDescriptor getAfdMedia(Context a, String path)
    {
        return testVideo(a, path);
    }

}
