package com.renitha.Activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.google.gson.Gson;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.renitha.Interface.APIService;
import com.renitha.Model.EventModel;
import com.renitha.Model.ImageSenderInfo;
import com.renitha.Model.ResponseModel;
import com.renitha.NetworkRelated.RetrofitApiClient;
import com.renitha.Pref.Pref;
import com.renitha.R;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddPictureComplaintActivity extends AppCompatActivity
{
    private ImageView imageView;
    private Button btnSave,btnAdd,btnUpload;
    private String str="";
    private static final String IMAGE_DIRECTORY = "/RenithaImage";
    Uri uri;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private LinearLayout linear_single,linear_both;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_customer);

        imageView       =   findViewById(R.id.img);
        btnSave         =   (Button) findViewById(R.id.btnFinish);
        btnAdd          =   (Button) findViewById(R.id.btnAdd);
        btnUpload       =   (Button) findViewById(R.id.btnUpload);
        linear_single   =   (LinearLayout) findViewById(R.id.linear_single);
        linear_both     =   (LinearLayout) findViewById(R.id.linear_both);

        imageView.setImageBitmap(CameraActivity.bitmap);

        btnSave.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                startActivity(new Intent(getApplicationContext(), ViewCustomerComplaints.class));
                overridePendingTransition(R.anim.enter, R.anim.exit);
            }
        });

        btnAdd.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                startActivity(new Intent(getApplicationContext(), CameraActivity.class));
                overridePendingTransition(R.anim.enter, R.anim.exit);
            }
        });
        btnUpload.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                String ticket_id             =   Pref.getInstance(getApplicationContext()).getTICKET_ID();
                fileUpload(str, new ImageSenderInfo(ticket_id));
            }
        });
        saveImage(getApplicationContext(), CameraActivity.bitmap);
    }

    public String saveImage(Context mContext, Bitmap bitmap){

        String mTimeStamp = new SimpleDateFormat("dd-MM-yyyy-HHmmsS").format(new Date());

       // String mImageName = "snap_"+mTimeStamp;

        ContextWrapper wrapper = new ContextWrapper(mContext);

        File file = wrapper.getDir("Images",MODE_PRIVATE);
        String randString =   getSaltString();
        file = new File(file, "renitha_"+randString+"_"+mTimeStamp+".jpg");
        try{

            OutputStream stream = null;

            stream = new FileOutputStream(file);

            bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);

            stream.flush();

            stream.close();

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        Uri mImageUri = Uri.parse(file.getAbsolutePath());
        str= file.getAbsolutePath();
        return str;
    }
    protected String getSaltString() {
        String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();
        while (salt.length() < 5) { // length of the random string.
            int index = (int) (rnd.nextFloat() * SALTCHARS.length());
            salt.append(SALTCHARS.charAt(index));
        }
        String saltStr = salt.toString();
        return saltStr;
    }
    public void fileUpload(String filePath, ImageSenderInfo imageSenderInfo) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("wait...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
        APIService apiInterface = RetrofitApiClient.getClient().create(APIService.class);

        Logger.addLogAdapter(new AndroidLogAdapter());

        File file = new File(filePath);
        //create RequestBody instance from file
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); //allow image and any other file

        // MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        Gson gson = new Gson();
        String patientData = gson.toJson(imageSenderInfo);

        RequestBody description = RequestBody.create(MultipartBody.FORM, patientData);

        // finally, execute the request
        Call<ResponseModel> call = apiInterface.fileUploadCust(description, body);
        call.enqueue(new Callback<ResponseModel>()
        {
            @Override
            public void onResponse( Call<ResponseModel> call, Response<ResponseModel> response)
            {
                Logger.d("Response: " + response);
                Log.d("Response: ","" + response);
                Log.d("Response: ","" + response.body());
                ResponseModel responseModel = response.body();
                progressDialog.dismiss();
                linear_single.setVisibility(View.GONE);
                linear_both.setVisibility(View.VISIBLE);
                if (response.body().isSuccess().equals(true))
                {
                    finish();
                    EventBus.getDefault().post(new EventModel("response", responseModel.getMessage()));
                    Logger.d("Response code " + response.code() +
                            " Response Message: " + responseModel.getMessage());
                    linear_single.setVisibility(View.GONE);
                    linear_both.setVisibility(View.VISIBLE);
                }
                else
                    {
                    EventBus.getDefault().post(new EventModel("response", "ResponseModel is NULL"));
                }
            }
            @Override
            public void onFailure(@NonNull Call<ResponseModel> call, @NonNull Throwable t)
            {
                Logger.d("Exception: " + t);
                EventBus.getDefault().post(new EventModel("response", t.getMessage()));
                progressDialog.dismiss();
            }
        });
    }
    @Override
    public void onBackPressed()
    {
        startActivity(new Intent(AddPictureComplaintActivity.this, CameraActivity.class));
        overridePendingTransition(R.anim.enter, R.anim.exit);
    }

}
