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.location.Location;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Toast;

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

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.SettingsClient;
import com.google.gson.Gson;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.renitha.Interface.APIService;
import com.renitha.Model.APIUrl;
import com.renitha.Model.EventModel;
import com.renitha.Model.ImageSenderInfo;
import com.renitha.Model.ResponseModel;
import com.renitha.Model.SetterLogin;
import com.renitha.NetworkRelated.RetrofitApiClient;
import com.renitha.Pref.Pref;
import com.renitha.R;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PictureDoneComplaintActivity extends AppCompatActivity
{
    private ImageView imageView;
    private Button btnSave,btnAdd,btnUpload,btnFinish;
    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);

        imageView       =   findViewById(R.id.img);
        btnSave         =   (Button) findViewById(R.id.btnSave);
        btnAdd          =   (Button) findViewById(R.id.btnAdd);
        btnUpload       =   (Button) findViewById(R.id.btnUpload);
        btnFinish       =   (Button) findViewById(R.id.btnFinish);
        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(), CustomerSignActivity.class));
                overridePendingTransition(R.anim.enter, R.anim.exit);
               // fileUpload("next");
               // String ticket_id             =   Pref.getInstance(getApplicationContext()).getTICKET_ID();
               // fileUpload(str, new ImageSenderInfo(ticket_id),"next");
            }
        });

        btnAdd.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                startActivity(new Intent(getApplicationContext(), CameraActivity.class));
                overridePendingTransition(R.anim.enter, R.anim.exit);
                //String ticket_id             =   Pref.getInstance(getApplicationContext()).getTICKET_ID();
               // fileUpload(str, new ImageSenderInfo(ticket_id),"add");
            //    fileUpload("add");
              //  startActivity(new Intent(PictureDoneComplaintActivity.this,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));
            //    fileUpload("add");
              //  startActivity(new Intent(PictureDoneComplaintActivity.this,CameraActivity.class));
             //   overridePendingTransition(R.anim.enter, R.anim.exit);
            }
        });

        btnFinish.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Pref.getInstance(getApplicationContext()).setTICKET_ID("");
                startActivity(new Intent(getApplicationContext(), ViewUserComplaints.class));
                overridePendingTransition(R.anim.enter, R.anim.exit);
            }
        });
        saveImage(getApplicationContext(), CameraActivity.bitmap);
    }
  /*  public String saveImage(Bitmap myBitmap)
    {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File wallpaperDirectory = new File(
                Environment.getDataDirectory() + IMAGE_DIRECTORY);
        // have the object build the directory structure, if needed.

        if (!wallpaperDirectory.exists())
        {
            Log.d("dirrrrrr", "" + wallpaperDirectory.mkdirs());
            wallpaperDirectory.mkdirs();
        }

        try
        {
            File f = new File(wallpaperDirectory, Calendar.getInstance()
                    .getTimeInMillis() + ".jpg");
            f.createNewFile();   //give read write permission
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            uri = Uri.fromFile(new File(f.getAbsolutePath()));
            str= f.getAbsolutePath();
            String mime = getMimeType(f.getAbsolutePath());
           // Pref.getInstance(getApplicationContext()).setPic(str);
            Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
            Log.d("TAG", "File Saved uri::--->" + uri);

            return f.getAbsolutePath();
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
        }
        return "";
    }

   */
  public String saveImage(Context mContext, Bitmap bitmap){

      String mTimeStamp = new SimpleDateFormat("dd-MM-yyyy-HHmmsS").format(new Date());
      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 static String getMimeType(String url)
    {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null)
        {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }
    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.fileUpload(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);
                btnFinish.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(PictureDoneComplaintActivity.this, CameraActivity.class));
        overridePendingTransition(R.anim.enter, R.anim.exit);
    }



 /*   public String saveImage(Bitmap myBitmap)
    {
        str= encodeImage(myBitmap);
        return "";
    }

    private String encodeImage(Bitmap bm)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG,50,baos);
        byte[] b = baos.toByteArray();
        String encImage = Base64.encodeToString(b, Base64.DEFAULT);

        return encImage;
    }

    private void fileUpload(final String actv)
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Saving...");
        progressDialog.show();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(100, TimeUnit.SECONDS)
                .writeTimeout(100, TimeUnit.SECONDS)
                .readTimeout(100, TimeUnit.SECONDS).build();
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        // set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        // add your other interceptors …
        // add logging as last interceptor
        httpClient.addInterceptor(logging);  // <-- this is the important line
 //.client(httpClient.build())


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(APIUrl.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        String login_id       =   Pref.getInstance(getApplicationContext()).getLoginId();
        String id             =   Pref.getInstance(getApplicationContext()).getTICKET_ID();
       String  photo_flag =   Pref.getInstance(getApplicationContext()).getPhotoFlag();
        APIService service = retrofit.create(APIService.class);
        Call<SetterLogin> call = service.setComplaintPhoto(id,"5",str,login_id,photo_flag);

        call.enqueue(new Callback<SetterLogin>()
        {
            @Override
            public void onResponse(Call<SetterLogin> call, Response<SetterLogin> response)
            {
                progressDialog.dismiss();
                if (response.body().getError().equals(true))
                {
                    Pref.getInstance(getApplicationContext()).setTICKET_ID(response.body().getLogin_id());
                    Pref.getInstance(getApplicationContext()).setPhotoFlag(response.body().getMessage());
                    if(actv.equals("next"))
                    {
                        startActivity(new Intent(PictureDoneComplaintActivity.this,CustomerSignActivity.class));
                        overridePendingTransition(R.anim.enter, R.anim.exit);
                    }
                    else if(actv.equals("add"))
                    {
                        startActivity(new Intent(PictureDoneComplaintActivity.this,CameraActivity.class));
                        overridePendingTransition(R.anim.enter, R.anim.exit);
                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Information saved Failed", Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void onFailure(Call<SetterLogin> call, Throwable t)
            {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(), "Information saved Failed", Toast.LENGTH_LONG).show();
            }
        });
    }

*/
}
