package br.com.trimsy.share;

import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;

import androidx.core.content.FileProvider;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class TrimsyShare extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) {
        final JSONObject payload = args != null ? args.optJSONObject(0) : null;
        if (payload == null) {
            callbackContext.error("missing_payload");
            return true;
        }
        if ("share".equals(action)) {
            cordova.getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    try {
                        share(payload);
                        callbackContext.success();
                    } catch (Exception e) {
                        callbackContext.error(e.getMessage() != null ? e.getMessage() : "share_failed");
                    }
                }
            });
            return true;
        }
        if ("save".equals(action)) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        save(payload);
                        callbackContext.success();
                    } catch (Exception e) {
                        callbackContext.error(e.getMessage() != null ? e.getMessage() : "save_failed");
                    }
                }
            });
            return true;
        }
        return false;
    }

    private void share(JSONObject payload) throws Exception {
        Activity act = cordova.getActivity();
        String title = payload.optString("title", "Trimsy One");
        String text = payload.optString("text", "");
        String mime = payload.optString("mime", "");
        String data = firstData(payload);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (data != null && data.length() > 0) {
            File file = writeCacheFile(data, payload.optString("name"), mime);
            Uri uri = FileProvider.getUriForFile(act, act.getPackageName() + ".cdv.core.file.provider", file);
            String sendMime = mime != null && mime.length() > 0 ? mime : guessMime(file.getName());
            intent.setType(sendMime);
            intent.putExtra(Intent.EXTRA_STREAM, uri);
            intent.setClipData(ClipData.newUri(act.getContentResolver(), title, uri));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setType("text/plain");
        }
        if (text.length() > 0) intent.putExtra(Intent.EXTRA_TEXT, text);
        if (title.length() > 0) intent.putExtra(Intent.EXTRA_SUBJECT, title);
        act.startActivity(Intent.createChooser(intent, title));
    }

    private void save(JSONObject payload) throws Exception {
        Activity act = cordova.getActivity();
        String data = firstData(payload);
        if (data == null || data.length() == 0) throw new Exception("missing_file");
        String name = payload.optString("name", "trimsy-" + System.currentTimeMillis());
        String mime = payload.optString("mime", guessMime(name));
        byte[] bytes = decodeData(data);
        if (Build.VERSION.SDK_INT >= 29) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
            values.put(MediaStore.MediaColumns.MIME_TYPE, mime);
            boolean image = mime != null && mime.indexOf("image/") == 0;
            Uri collection = image
                ? MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
                : MediaStore.Downloads.EXTERNAL_CONTENT_URI;
            if (!image) values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
            ContentResolver cr = act.getContentResolver();
            Uri uri = cr.insert(collection, values);
            if (uri == null) throw new Exception("save_failed");
            OutputStream os = cr.openOutputStream(uri);
            if (os == null) throw new Exception("save_failed");
            os.write(bytes);
            os.close();
            return;
        }
        File dir = Environment.getExternalStoragePublicDirectory(
            mime != null && mime.indexOf("image/") == 0 ? Environment.DIRECTORY_PICTURES : Environment.DIRECTORY_DOWNLOADS
        );
        if (!dir.exists()) dir.mkdirs();
        File out = new File(dir, name);
        FileOutputStream fos = new FileOutputStream(out);
        fos.write(bytes);
        fos.close();
    }

    private String firstData(JSONObject payload) {
        String file = payload.optString("file", "");
        if (file.length() > 0) return file;
        return payload.optString("image", "");
    }

    private File writeCacheFile(String data, String name, String mime) throws Exception {
        if (name == null || name.length() == 0) {
            String ext = mime != null && mime.indexOf("pdf") >= 0 ? ".pdf" : ".jpg";
            name = "trimsy-" + System.currentTimeMillis() + ext;
        }
        File dir = new File(cordova.getActivity().getCacheDir(), "trimsy-share");
        if (!dir.exists()) dir.mkdirs();
        File file = new File(dir, name.replaceAll("[^A-Za-z0-9._-]", "_"));
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(decodeData(data));
        fos.close();
        return file;
    }

    private byte[] decodeData(String data) {
        int comma = data.indexOf(',');
        String raw = comma >= 0 ? data.substring(comma + 1) : data;
        return Base64.decode(raw, Base64.DEFAULT);
    }

    private String guessMime(String name) {
        String lower = String.valueOf(name).toLowerCase();
        if (lower.endsWith(".pdf")) return "application/pdf";
        if (lower.endsWith(".png")) return "image/png";
        if (lower.endsWith(".webp")) return "image/webp";
        return "image/jpeg";
    }
}
