package com.autotech.we1l.file_upload_utils;

import android.support.annotation.NonNull;
import android.webkit.MimeTypeMap;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.autotech.we1l.tools.ConstantsKt.ATTR_ERROR_CODE;
import static com.autotech.we1l.tools.ConstantsKt.CODE_OK;


public class UploadRequest {

    private static UploadRequest instance;

    public static synchronized UploadRequest getInstance() {
        if (instance == null) {
            instance = new UploadRequest();
            return instance;
        }
        return instance;
    }

    public void uploadFile(String requestUrl, Map<String, String> inputMap, OnUploadListener onUploadListener, String fileAttrName) {

        File file = new File((inputMap.get(fileAttrName)));
        String path = file.getAbsolutePath();

        new Thread() {
            @Override
            public void run() {

                String path2 = path.replaceAll(" ", "%20");

                String extension = MimeTypeMap.getFileExtensionFromUrl(path2);
                if (extension.isEmpty()) {
                    extension = path.substring(path.lastIndexOf(".") + 1);
                }
                String contentType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

                OkHttpClient.Builder builder1 = new OkHttpClient.Builder();
                builder1.writeTimeout(60, TimeUnit.SECONDS);
                builder1.readTimeout(60, TimeUnit.SECONDS);

                OkHttpClient client = builder1.build();

                RequestBody fileBody = RequestBody.create(MediaType.parse((contentType)), file);

                MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart(fileAttrName, path.substring(path.lastIndexOf("/") + 1), fileBody);

                inputMap.remove(fileAttrName);

                for (String key : inputMap.keySet()) {
                    builder.addFormDataPart(key, (inputMap.get(key)));
                }

                RequestBody requestBody = builder.build();

                Request request = new Request.Builder().url(requestUrl).post(requestBody).build();

                client.newCall(request).enqueue(new Callback() {

                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        onUploadListener.onError(e);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String responseString = (response.body()).string();
                        try {
                            JSONObject responseJSON = new JSONObject(responseString);
                            if (responseJSON.getInt(ATTR_ERROR_CODE) == CODE_OK) {
                                onUploadListener.onSuccess(responseJSON);
                            } else {
                                onUploadListener.onFailed(responseJSON);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }.start();

    }

    public interface OnUploadListener {
        default void onSuccess(JSONObject response) {
        }

        default void onFailed(JSONObject response) {
        }

        default void onError(Exception e) {
        }
    }

}
