package com.omixlab.panopainter;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;

import java.io.File;

public class MainActivity extends PlatformActivity {
    static {
        for (String lib : Platform.Libs)
            System.loadLibrary(lib);
        System.loadLibrary("native-lib");
    }

    private ClipboardManager clipboard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //init_vr(getAssets());
        super.onCreate(savedInstanceState);
        clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        checkPermissionReadStorage();
        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {

                Rect r = new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);

                int screenHeight = getWindow().getDecorView().getRootView().getHeight();
                int heightDifference = screenHeight - (r.bottom - r.top);
                Log.d("Keyboard Size", "Size: " + heightDifference);
                View rv = getWindow().getDecorView().getRootView();

                contentRectChanged(rv.getWidth(), rv.getHeight(), r.left, r.top, r.right, r.bottom);
            }
        });
    }

    public native void init_vr(AssetManager am);
    public native void pickFileCallback(String path);
    public native void pickExternalCallback(String path);
    public native void contentRectChanged(int wnd_w, int wnd_h, int rect_left, int rect_top, int rect_right, int rect_bottom);

    public boolean createDir(String path)
    {
        File dir = new File(path);

        if (!dir.exists())
        {
            boolean success = dir.mkdirs();
            if (success)
                Log.v("PanoPainterJava", "create path " + dir.getAbsolutePath());
            else
                Log.v("PanoPainterJava", "create path failed " + dir.getAbsolutePath());
            return success;
        }
        Log.v("PanoPainterJava", "create path already existed " + dir.getAbsolutePath());
        return true;
    }

    public void setRootPath()
    {
        Log.v("PanoPainterJava", "permission granted");
        File d = Environment.getExternalStorageDirectory();
        File pano_dir = new File(d, "PanoPainter");

        if (!pano_dir.exists())
        {
            if (pano_dir.mkdirs())
                Log.v("PanoPainterJava", "create path " + pano_dir.getAbsolutePath());
            else
                Log.v("PanoPainterJava", "create path failed");

        }
        File frames = new File(pano_dir.getAbsolutePath(), "frames");
        if (!frames.exists())
        {
            if (frames.mkdirs())
                Log.v("PanoPainterJava", "create path " + frames.getAbsolutePath());
            else
                Log.v("PanoPainterJava", "create path failed: " + frames.getAbsolutePath());

        }
        // brushes
        File brushes = new File(pano_dir.getAbsolutePath(), "brushes");
        if (!brushes.exists())
        {
            if (brushes.mkdirs())
                Log.v("PanoPainterJava", "create path " + brushes.getAbsolutePath());
            else
                Log.v("PanoPainterJava", "create path failed: " + brushes.getAbsolutePath());

        }
        File brush_thumbs = new File(brushes.getAbsolutePath(), "thumbs");
        if (!brush_thumbs.exists())
        {
            if (brush_thumbs.mkdirs())
                Log.v("PanoPainterJava", "create path " + brush_thumbs.getAbsolutePath());
            else
                Log.v("PanoPainterJava", "create path failed: " + brush_thumbs.getAbsolutePath());

        }
        // patterns
        File patterns = new File(pano_dir.getAbsolutePath(), "patterns");
        if (!patterns.exists())
        {
            if (patterns.mkdirs())
                Log.v("PanoPainterJava", "create path " + patterns.getAbsolutePath());
            else
                Log.v("PanoPainterJava", "create path failed: " + patterns.getAbsolutePath());

        }
        File patterns_thumbs = new File(patterns.getAbsolutePath(), "thumbs");
        if (!patterns_thumbs.exists())
        {
            if (patterns_thumbs.mkdirs())
                Log.v("PanoPainterJava", "create path " + patterns_thumbs.getAbsolutePath());
            else
                Log.v("PanoPainterJava", "create path failed: " + patterns_thumbs.getAbsolutePath());

        }
        // settings
        File settings = new File(pano_dir.getAbsolutePath(), "settings");
        if (!settings.exists())
        {
            if (settings.mkdirs())
                Log.v("PanoPainterJava", "create path " + settings.getAbsolutePath());
            else
                Log.v("PanoPainterJava", "create path failed: " + settings.getAbsolutePath());

        }
        pickExternalCallback(pano_dir.getAbsolutePath());
    }
    public void checkPermissionReadStorage(){
        Log.v("PanoPainterJava", "permission checking");
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
            setRootPath();
        } else {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                // Should we show an explanation?
            /*if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                Log.v("MainActivity", "permission explanation");


            } else {
*/
                // No explanation needed, we can request the permission.

                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                Log.v("PanoPainterJava", "permission request");

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
                //          }
            } else {
                Log.v("PanoPainterJava", "permission already granted");
                setRootPath();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                //premission to read storage
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    setRootPath();
                } else {
                    Log.v("PanoPainterJava", "permission denied");

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    //Toast.makeText(this, "We Need permission Storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    public String getDataPath() {
        return getExternalFilesDir(null).getAbsolutePath();
    }

    public float getDensity()
    {
        return getResources().getDisplayMetrics().density;
    }

    public String getClipboardText()
    {
        try
        {
            return clipboard.hasPrimaryClip() ? clipboard.getPrimaryClip().getItemAt(0).getText().toString() : "";
        }
        catch (Exception e)
        {
            return "";
        }
    }

    public boolean setClipboardText(String s)
    {
        try
        {
            clipboard.setPrimaryClip(ClipData.newPlainText("PanoPainter text", s));
            return true;
        }
        catch (Exception e)
        {
            // fail silently
            return false;
        }
    }

    public void pickFile()
    {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        startActivityForResult(Intent.createChooser(intent, "Select a file"), 1);
        Log.v("PanoPainterJava", "pick start");
    }

    public void pickFileSave()
    {
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        startActivityForResult(Intent.createChooser(intent, "Select a file"), 1);
        Log.v("PanoPainterJava", "pick save start");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            //File myFile = new File(uri.getPath());
            //String path = myFile.getAbsolutePath();
            String path = null;
            try {
                path = FileUtils.getPath(this, uri);
                Log.v("PanoPainterJava", "pick selected " + path);
                if (path != null)
                    pickFileCallback(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
