package com.autotech.we1l.file_upload_utils;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.autotech.we1l.app.AppLanguage;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;

import pub.devrel.easypermissions.EasyPermissions;

import static com.autotech.we1l.tools.ConstantsKt.ATTR_IMAGE;
import static com.autotech.we1l.tools.ConstantsKt.FOLDER_NAME;
import static com.autotech.we1l.tools.ConstantsKt.PACKAGE_NAME;
import static com.autotech.we1l.tools.ConstantsKt.SENT_FILES_FOLDER_NAME;
import static com.autotech.we1l.tools.Language.dialog_opt_camera;
import static com.autotech.we1l.tools.Language.dialog_opt_gallery;
import static com.autotech.we1l.tools.Language.dialog_opt_pick_file;
import static com.autotech.we1l.tools.Language.err_file_pick_failed;
import static com.autotech.we1l.tools.Language.prompt_send_photo;


public class UploadFileManager_Fragment {

    // PERMISSIONS:
    public final String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    // PERMISSIONS REQUESTS:
    public static final int CAMERA_STORAGE_REQUEST = 1;
    public static final int GALLERY_STORAGE_REQUEST = 2;

    // REQUEST CODES
    private static final int CAMERA_REQUEST = 1;
    public static final int GALLERY_REQUEST = 2;
    public static final int PICKFILE_REQUEST = 3;

    private String uploadedFilePath;
    private File sentFile;

    /*
        Image:
     */
    private String fileName;
    private Uri fileUri;

    public void launchDialog(Fragment fragment, boolean imagesOnly) {
        String[] items;
        if (imagesOnly) {
            items = new String[]{AppLanguage.INSTANCE.getString(dialog_opt_camera), AppLanguage.INSTANCE.getString(dialog_opt_gallery)};
        } else {
            items = new String[]{AppLanguage.INSTANCE.getString(dialog_opt_camera), AppLanguage.INSTANCE.getString(dialog_opt_gallery),
                    AppLanguage.INSTANCE.getString(dialog_opt_pick_file)};
        }

        new AlertDialog.Builder((fragment.getContext()))
                .setItems(items, (dialogInterface, which) -> {
                    switch (which) {
                        case 0: {
                            if (EasyPermissions.hasPermissions(fragment.getContext(), perms)) {
                                launchCamera(fragment);
                            } else {
                                EasyPermissions.requestPermissions((fragment.getActivity()),
                                        AppLanguage.INSTANCE.getString(prompt_send_photo), CAMERA_STORAGE_REQUEST, perms);
                            }
                            break;
                        }
                        case 1: {
                            if (EasyPermissions.hasPermissions(fragment.getContext(), perms)) {
                                launchGallery(fragment);
                            } else {
                                EasyPermissions.requestPermissions((fragment.getActivity()),
                                        AppLanguage.INSTANCE.getString(prompt_send_photo), GALLERY_STORAGE_REQUEST, perms);
                            }
                            break;
                        }
                        case 2: {
                            launchFilePicker(fragment);
                            break;
                        }
                    }
                }).show();
    }

    public void launchFilePicker(Fragment fragment) {
        fragment.startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("application/pdf"), PICKFILE_REQUEST);
    }

    public void launchGallery(Fragment fragment) {
        fragment.startActivityForResult(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI), GALLERY_REQUEST);
    }

    public void launchCamera(Fragment fragment) {
        fileName = System.currentTimeMillis() + ".jpg";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            File appDirectory = new File((fragment.getActivity()).getCacheDir(), FOLDER_NAME);
            if (!appDirectory.exists()) {
                appDirectory.mkdirs();
            }
            File sentDirectory = new File(appDirectory, SENT_FILES_FOLDER_NAME);
            if (!sentDirectory.exists()) {
                sentDirectory.mkdirs();
            }
            sentFile = new File(sentDirectory, fileName);
            try {
                sentFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            fileUri = FileProvider.getUriForFile(fragment.getActivity(), PACKAGE_NAME + ".fileprovider", sentFile);
        } else {
            File sentDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + FOLDER_NAME + SENT_FILES_FOLDER_NAME);
            if (!sentDirectory.exists()) {
                sentDirectory.mkdirs();
            }
            sentFile = new File(sentDirectory, fileName);
            try {
                sentFile.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
            fileUri = Uri.fromFile(sentFile);
        }
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        fragment.startActivityForResult(cameraIntent, CAMERA_REQUEST);
    }


    public void onResult(int requestCode, int resultCode, Fragment fragment,
                         Intent data, int qualityPercentage, OnLoadListener onLoadListener) throws IOException {
        Bitmap imageBitmap = null;
        switch (requestCode) {
            case GALLERY_REQUEST: {
                if (resultCode == Activity.RESULT_OK) {
                    fileUri = data.getData();
                    imageBitmap = MediaStore.Images.Media.getBitmap((fragment.getActivity()).getContentResolver(),
                            fileUri);

                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

                    File sentFilesPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + FOLDER_NAME + SENT_FILES_FOLDER_NAME);
                    if (!sentFilesPath.exists()) {
                        sentFilesPath.mkdirs();
                    }

                    sentFile = new File(sentFilesPath, ATTR_IMAGE + System.currentTimeMillis() + ".jpg");
                    imageBitmap.compress(Bitmap.CompressFormat.JPEG, qualityPercentage, bytes);

                    try {
                        sentFile.createNewFile();
                        FileOutputStream fo = new FileOutputStream(sentFile);
                        fo.write(bytes.toByteArray());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    onLoadListener.onLoad(sentFile, imageBitmap, false);
                }
                break;
            }
            case CAMERA_REQUEST: {
                if (resultCode == Activity.RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        try {
                            imageBitmap = MediaStore.Images.Media.getBitmap((fragment.getActivity()).getContentResolver(),
                                    fileUri);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
                        bmpFactoryOptions.inJustDecodeBounds = false;

                        imageBitmap = BitmapFactory.decodeFile(fileUri.getPath(), bmpFactoryOptions);
                    }
                    if (imageBitmap == null) {
                        return;
                    }
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    File sentFilesPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + FOLDER_NAME + SENT_FILES_FOLDER_NAME);
                    if (!sentFilesPath.exists()) {
                        sentFilesPath.mkdirs();
                    }
                    sentFile = new File(sentFilesPath, ATTR_IMAGE + System.currentTimeMillis() + ".jpg");
                    imageBitmap.compress(Bitmap.CompressFormat.JPEG, qualityPercentage, bytes);

                    try {
                        sentFile.createNewFile();
                        FileOutputStream fo = new FileOutputStream(sentFile);
                        fo.write(bytes.toByteArray());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    onLoadListener.onLoad(sentFile, imageBitmap, false);
                    break;
                }
            }
            case PICKFILE_REQUEST: {
                if (resultCode == Activity.RESULT_OK) {
                    if (data.getData() != null) {
                        Uri selectedFileUri = data.getData();
                        try {
                            sentFile = new File(URLDecoder.decode(RealPathUtil.getRealPath(fragment.getContext(), selectedFileUri)));
                        } catch (Exception ignored) {
                            Toast.makeText(fragment.getContext(), AppLanguage.INSTANCE.getString(err_file_pick_failed), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        onLoadListener.onLoad(sentFile, null, true);
                    }
                }
                break;
            }
        }
    }

    public void clear() {
        sentFile = null;
        fileName = "";
        fileUri = null;
    }

    public File getSentFile() {
        return sentFile;
    }

    public interface OnLoadListener {
        void onLoad(File file, Bitmap bitmap, boolean isFile);
    }
}
