package com.pixelnx.localhelp.ui.user;


import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;

import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;

import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.ParsedRequestListener;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.DexterError;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import com.pixelnx.localhelp.R;
import com.pixelnx.localhelp.model.ModelUserData;
import com.pixelnx.localhelp.utils.Consts;
import com.pixelnx.localhelp.utils.ProjectUtils;
import com.pixelnx.localhelp.utils.sharedpref.SharedPref;
import com.pixelnx.localhelp.utils.widgets.CustomEditText;
import com.pixelnx.localhelp.utils.widgets.CustomTextMedium;
import com.squareup.picasso.Picasso;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class ActivityCustomerPro extends Activity implements View.OnClickListener {
    ImageView backIv;
SharedPref sharedPref;
    ModelUserData modelUserData;
    Context mContext;
    CustomEditText name;
    CustomEditText mobile;
    CustomEditText addEmail;
    CustomEditText pass;
    CustomEditText wardNumber;
    CustomEditText houseTv;
    CustomEditText townTv;
    CustomEditText district;
    CustomTextMedium update;
    CustomTextMedium tvNameHead;
    RelativeLayout imgSelect;
    private int gallery = 1;
    private int camera = 2;
    private static final String IMAGE_DIRECTORY = "/homeDeliveryApp";
    Uri mCapturedImageURI;
    File file;
    String path="";
    CircleImageView imgProfile;
    String requiredField="Required field";
    String cancel="Cancel";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vendor_profile);
        init();
    }
    void init(){
        mContext= ActivityCustomerPro.this;
        sharedPref = SharedPref.getInstance(mContext);
        modelUserData = sharedPref.getUser(Consts.Status.SP);
        backIv=findViewById(R.id.backIv);
        tvNameHead=findViewById(R.id.tvNamehead);
        tvNameHead.setText(R.string.name);
        imgSelect=findViewById(R.id.imgSelect);
        imgProfile=findViewById(R.id.imgProfile);
        imgSelect.setOnClickListener(this);
        pass=findViewById(R.id.pass);
        update=findViewById(R.id.update);
        update.setOnClickListener(this);
        houseTv=findViewById(R.id.houseTv);
        townTv=findViewById(R.id.towntv);
        district=findViewById(R.id.district);
        wardNumber=findViewById(R.id.wardnum);
        backIv.setOnClickListener(this);
        name=findViewById(R.id.name);
        mobile=findViewById(R.id.mobile);
        addEmail=findViewById(R.id.addemail);
        name.setText(""+modelUserData.getData().getUserName());
        addEmail.setText(""+modelUserData.getData().getUserEmail());
        mobile.setText(""+modelUserData.getData().getUserMobile());
        Picasso.get()
                .load(Consts.Status.BASE_IMAGE_URL+"users/" + modelUserData.getData().getUserImage())
                .placeholder(R.drawable.noimage)
                .into(imgProfile);

        String add=modelUserData.getData().getAddress().trim();
        if(add.contains("|")){
            String str=add.replace("|",",");
            String []parts = str.split(",");

            wardNumber.setText(parts[1]);
            houseTv.setText(parts[3]);
            townTv.setText(parts[2]);
            district.setText(parts[0]);
        }

    }
    void apiUpdate(){

        if(file!=null){


            String address= district.getText().toString()+"|"+wardNumber.getText().toString()+"|"+townTv.getText().toString()+"|"+houseTv.getText().toString();
            ProjectUtils.showProgressDialog(mContext, false, "Loading...");
            AndroidNetworking.upload(Consts.Status.BASE_URL +Consts.Status.API_USER_UPDATE)
                    .addMultipartParameter("user_id",""+modelUserData.getData().getUserId())
                    .addMultipartParameter("u_name",""+name.getText().toString())
                    .addMultipartParameter("u_mobile",""+mobile.getText().toString())
                    .addMultipartParameter("u_email",""+addEmail.getText().toString())
                    .addMultipartParameter("u_pwd",""+pass.getText().toString())
                    .addMultipartParameter("u_latitude",""+modelUserData.getData().getLatitude())
                    .addMultipartParameter("u_longitude",""+modelUserData.getData().getLongitude())
                    .addMultipartParameter("address",""+address)
                    .addMultipartFile("u_image",file)
                    .setPriority(Priority.IMMEDIATE)
                    .setTag(Consts.Status.SEARCH_API)
                    .build()
                    .getAsObject(ModelUserData.class, new ParsedRequestListener<ModelUserData>() {
                        @Override
                        public void onResponse(ModelUserData response) {
                            ProjectUtils.pauseProgressDialog();
                            if(response.getStatus().equalsIgnoreCase("1")) {
                                ProjectUtils.pauseProgressDialog();

                               sharedPref = SharedPref.getInstance(mContext);
                                sharedPref.setBooleanValue(Consts.Status.IS_REGIS, true);
                                SharedPref.setUser(Consts.Status.SP, response);
                                Toast.makeText(mContext,"Updated Sucessfully...",Toast.LENGTH_SHORT).show();

                            }else{
                                Toast.makeText(mContext,""+response.getMsg(),Toast.LENGTH_SHORT).show();
                            }

                        }

                        @Override
                        public void onError(ANError anError) {
                       Toast.makeText(mContext,"Something went wrong ",Toast.LENGTH_SHORT).show();
                        }
                    });

        }else{
            String address= district.getText().toString()+"|"+wardNumber.getText().toString()+"|"+townTv.getText().toString()+"|"+houseTv.getText().toString();
            ProjectUtils.showProgressDialog(mContext, false, "Loading...");
            AndroidNetworking.post(Consts.Status.BASE_URL +Consts.Status.API_USER_UPDATE)
                    .addBodyParameter("user_id",""+modelUserData.getData().getUserId())
                    .addBodyParameter("u_name",""+name.getText().toString())
                    .addBodyParameter("u_mobile",""+mobile.getText().toString())
                    .addBodyParameter("u_email",""+addEmail.getText().toString())
                    .addBodyParameter("u_pwd",""+pass.getText().toString())
                    .addBodyParameter("u_latitude",""+modelUserData.getData().getLatitude())
                    .addBodyParameter("u_longitude",""+modelUserData.getData().getLongitude())
                    .addBodyParameter("address",""+address)
                    .setPriority(Priority.IMMEDIATE)
                    .setTag(Consts.Status.SEARCH_API)
                    .build()
                    .getAsObject(ModelUserData.class, new ParsedRequestListener<ModelUserData>() {
                        @Override
                        public void onResponse(ModelUserData response) {
                            ProjectUtils.pauseProgressDialog();
                            if(response.getStatus().equalsIgnoreCase("1")){

                                Toast.makeText(mContext,"Updated Sucessfully...",Toast.LENGTH_SHORT).show();
                                ProjectUtils.pauseProgressDialog();
                              sharedPref = SharedPref.getInstance(mContext);
                                sharedPref.setBooleanValue(Consts.Status.IS_REGIS,true);
                                SharedPref.setUser(Consts.Status.SP,response);}
                        }

                        @Override
                        public void onError(ANError anError) {

                            ProjectUtils.pauseProgressDialog();
                        }
                    });

        }



    }

    private void selectImage() {
        final CharSequence[] items = {"Camera", "Gallery", cancel};

        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
        builder.setTitle("Select Image From ");

        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                if (items[i].equals("Camera")) {
                    takePhotoFromCamera();

                } else if (items[i].equals("Gallery")) {
                    choosePhotoFromGallery();

                } else if (items[i].equals(cancel)) {
                    dialogInterface.dismiss();

                }
            }
        });

        builder.show();

    }
    public void choosePhotoFromGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(galleryIntent, gallery);
    }

    private void takePhotoFromCamera() {

        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "Image File name");
        mCapturedImageURI = mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
        ((Activity) mContext).startActivityForResult(intentPicture, camera);
    }



    public String saveImage(Bitmap myBitmap) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        File wallpaperDirectory = new File(
                Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);

        if (!wallpaperDirectory.exists()) {
            wallpaperDirectory.mkdirs();
        }

        try {
            File f = new File(wallpaperDirectory, Calendar.getInstance()
                    .getTimeInMillis() + ".jpg");
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(mContext,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();


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



    private void requestPermission() {

        Dexter.withActivity((Activity) mContext)
                .withPermissions(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {

                        if (report.areAllPermissionsGranted()) {

                            selectImage();

                        }else{
                            openSettingsDialog();
                        }


                        if (report.isAnyPermissionPermanentlyDenied()) {


                            openSettingsDialog();


                        }

                    }


                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }

                }).
                withErrorListener(new PermissionRequestErrorListener() {
                    @Override
                    public void onError(DexterError error) {
                        Toast.makeText(mContext, "Error occurred! ", Toast.LENGTH_SHORT).show();
                    }
                })
                .onSameThread()
                .check();

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (requestCode == gallery) {
            if (data != null) {
                Uri contentURI = data.getData();


                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), contentURI);
                    path = saveImage(bitmap);
                    file = new File(path);

                    imgProfile.setImageBitmap(bitmap);

                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(mContext, "Failed!", Toast.LENGTH_SHORT).show();
                }

            }

        } else if (requestCode == camera) {




            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), mCapturedImageURI);
               path = saveImage(bitmap);
                file = new File(path);

                imgProfile.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }



        }

    }

    private void openSettingsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("Need Permissions");
        builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
        builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();

                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", mContext.getPackageName(), null);
                intent.setData(uri);
                startActivityForResult(intent, 101);
            }
        });

        builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.backIv:
                onBackPressed();
                break;
            case R.id.update:
                if(name.getText().toString().isEmpty()){
                    name.requestFocus();
                    name.setError(requiredField);
                }else{
                    if(addEmail.getText().toString().isEmpty()){
                        addEmail.requestFocus();
                        addEmail.setError(requiredField);
                    }else{
                if(mobile.getText().toString().isEmpty()){
                    mobile.requestFocus();
                    mobile.setError(requiredField);
                }else{
                    if(wardNumber.getText().toString().isEmpty()){
                        wardNumber.requestFocus();
                        wardNumber.setError(requiredField);
                    }else{
                        if(townTv.getText().toString().isEmpty()){
                            townTv.requestFocus();
                            townTv.setError(requiredField);
                        }else{
                            if(houseTv.getText().toString().isEmpty()){
                                houseTv.requestFocus();
                                houseTv.setError(requiredField);
                            }else{
                                if(district.getText().toString().isEmpty()){
                                    district.setError(requiredField);
                                    district.requestFocus();
                                }else{
                              apiUpdate();}
                            }}}}}}
                break;
            case R.id.imgSelect:
                if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(mContext, "Take Permission first", Toast.LENGTH_SHORT).show();
                    requestPermission();

                }else{
                    selectImage();}
                break;
        }

    }
}
