package com.seatel.mobilehall.util;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.seatel.mobilehall.BuildConfig;
import com.seatel.mobilehall.data.network.SeatelStringRequest;

import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class MultipartEntityRequest extends SeatelStringRequest {

    private File mFile;
    private final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    private String bodyContentType;
    private String mType = "images";

    public static MultipartEntityRequest with(Context context) {
        return new MultipartEntityRequest(context);
    }

    public MultipartEntityRequest(Context context) {
        super(context);
        setContentType(null);
    }

    public MultipartEntityRequest setType(String type) {
        this.mType = type;
        return this;
    }

    public MultipartEntityRequest setFile(File file) {
        this.mFile = file;
        return this;
    }

    @Override
    public Map<String, String> getAuthHeader() {
        Map<String, String> stringStringMap = new HashMap<>();
        stringStringMap.put("x-api-key", BuildConfig.CLIENT_ID);
        return stringStringMap;
    }


    @Override
    public String onGetBodyContentType() {
        if (bodyContentType == null || bodyContentType.isEmpty()) {
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntityBuilder.setLaxMode().setBoundary("XX.").setCharset(StandardCharsets.UTF_8);
            multipartEntityBuilder.addTextBody("type", mType);
            multipartEntityBuilder.addBinaryBody("files", mFile, ContentType.create("image/jpeg"), mFile.getName());
            bodyContentType = multipartEntityBuilder.build().getContentType().getValue();
        }
        return bodyContentType;
    }

    @Override
    public String getContentType() {
        return onGetBodyContentType();
    }


    @Override
    public byte[] onGetBody() {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            multipartEntityBuilder.build().writeTo(bos);
        } catch (IOException e) {
            VolleyLog.e("IOException writing to ByteArrayOutputstream");
        }
        return bos.toByteArray();
    }


    @Override
    public int getMethod() {
        return Request.Method.POST;
    }

    @Override
    public String getFunctionName() {
        return Constant.UPLOAD_IMAGE;
    }

    public void upLoadImage(Response.Listener<String> listener) {

        onGetBodyContentType();
        execute(listener);
    }
}