package com.pixelnx.localhelp.ui.storeitems;


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.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;

import android.widget.ScrollView;
import android.widget.Spinner;
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.androidnetworking.interfaces.StringRequestListener;
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.ModelSearchItem;
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.CustomTextMedium;
import com.pixelnx.localhelp.utils.widgets.CustomTextSemiBold;
import com.squareup.picasso.Picasso;

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

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

public class ActivityAddItem extends Activity implements View.OnClickListener {
Context mContext;
ImageView backIv;
    SharedPref sharedPref;
    ModelUserData modelUserData;
    CustomTextMedium addItems;
    CustomTextMedium selectImg;
    CustomTextMedium chooseWt;
   String userId="";
   String catId="";
   String unit="";
   String itemId="";
    String tag="";
    Spinner spinner;
    Spinner spinnerUnit;
    String path="";
    ArrayList<String> strings;
    ArrayList<String> stringUnits;
    ArrayList<ModelCategory> modelCategories;
    EditText etName;
    EditText quantity;
    EditText etRate;
    EditText weight;
    EditText etRateMRP;


    int gallery = 1;
    int camera = 2;
    private static final String IMAGE_DIRECTORY = "/homeDeliveryApp";
    Uri mCapturedImageURI;
    File file;
    ImageView  imageSave;
    CustomTextSemiBold heading;
    ScrollView scrollView;
    String cancel="Cancel";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_item);
        mContext=ActivityAddItem.this;
        sharedPref = SharedPref.getInstance(mContext);
        modelUserData = sharedPref.getUser(Consts.Status.SP);
        userId=modelUserData.getData().getUserId();
        spinner=findViewById(R.id.spinner);
        categoryAll();
        itemUnit();
        initial();

    }
    void itemUnit(){
        AndroidNetworking.post(Consts.Status.BASE_URL + Consts.Status.GET_ITEM_UNIT_API)
                .setPriority(Priority.IMMEDIATE)
                .setTag(Consts.Status.SEARCH_API)
                .build()
                .getAsObject(ModelUnit.class, new ParsedRequestListener<ModelUnit>() {
                    @Override
                    public void onResponse(ModelUnit response) {
                        if(response.getStatus().equalsIgnoreCase("1")){
                            stringUnits=new ArrayList<>();
                            for(int i=0;i<response.getUnitData().size();i++){

                                if (getIntent().hasExtra("update")){
                                    if(response.getUnitData().get(i).getUnitName().equalsIgnoreCase(""+unit)){
                                        stringUnits.add(0,""+response.getUnitData().get(i).getUnitName());
                                    }else{
                                        stringUnits.add(""+response.getUnitData().get(i).getUnitName());
                                    }

                                }else{

                                        stringUnits.add(""+response.getUnitData().get(i).getUnitName());

                                }
                            }
                            ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_item, stringUnits);
                            stringArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            spinnerUnit.setAdapter(stringArrayAdapter);
                        }

                    }

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

                    }
                });

}
    void initial(){

        scrollView=findViewById(R.id.scrollView);

        backIv=findViewById(R.id.backIv);
        etRateMRP=findViewById(R.id.etRateMRP);
        weight=findViewById(R.id.weight);
        chooseWt=findViewById(R.id.chsnWt);
        imageSave=findViewById(R.id.img);
        selectImg=findViewById(R.id.selectImg);
        selectImg.setOnClickListener(this);

        etName=findViewById(R.id.etName);
        etRate=findViewById(R.id.etRate);
        quantity=findViewById(R.id.quantity);
        addItems=findViewById(R.id.addItems);

        spinnerUnit=findViewById(R.id.spinnerUnit);
        backIv.setOnClickListener(this);

        spinner.setPrompt("Select Category");

        if(getIntent().hasExtra("update")){
            tag="update";
             ModelSearchItem.Data data =(ModelSearchItem.Data) getIntent().getSerializableExtra("data");
heading=findViewById(R.id.Heading);
addItems.setText("Update Items");
heading.setText("Update Items");
itemId=data.getSubCatId();

            if(!data.getItemMrp().isEmpty()){
                etRateMRP.setText(""+data.getItemMrp());
            }
etName.setText(""+data.getSubCatName());
etRate.setText(""+data.getRate());
quantity.setText(""+data.getStockQnt());
weight.setText(""+data.getItemStockWeight());
            Picasso
               .get()
                    .load(Consts.Status.BASE_IMAGE_URL + data.getImage())
                    .placeholder(R.drawable.noimagecart)
                    .into(imageSave);


             unit=""+data.getQntUnit();
             chooseWt.setText(""+data.getQntUnit());


            if(modelCategories!=null){
            for(int j=0;j<modelCategories.size();j++){

           if(data.getMainCatId().equalsIgnoreCase(""+modelCategories.get(j).getId())) {
               if(strings!=null){
              strings.add(0,modelCategories.get(j).getTitle());
               ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_item, strings);
               stringArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
               spinner.setAdapter(stringArrayAdapter);
               }

           }

           }}else{
                catId=data.getMainCatId();
            }



        }


        addItems.setOnClickListener(this);

        spinnerUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                chooseWt.setText(""+stringUnits.get(i));
                unit=""+stringUnits.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                throw new UnsupportedOperationException();
            }
        });
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

if(modelCategories != null) {
    for (int x = 0; x < modelCategories.size(); x++) {
        if (spinner.getSelectedItem().equals("" + modelCategories.get(x).getTitle())) {
            catId = modelCategories.get(x).getId();


        }
    }
}
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                throw new UnsupportedOperationException();
            }
        });

    }


    void categoryAll(){
        ProjectUtils.showProgressDialog(mContext, false, "Loading...");

        AndroidNetworking.post(Consts.Status.BASE_URL + Consts.Status.ALLCATEGORY_API)
                .setPriority(Priority.IMMEDIATE)
                .setTag(Consts.Status.SEARCH_API)
                .build()
                .getAsString(new StringRequestListener() {
                    @Override
                    public void onResponse(String response) {

                        ProjectUtils.pauseProgressDialog();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray jsonArray = jsonObject.getJSONArray("categoryData");
                            strings = new ArrayList<>();
                            modelCategories = new ArrayList<>();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                                strings.add("" + jsonObject1.getString("catName"));
                                ModelCategory modelCategory = new ModelCategory();
                                modelCategory.setId("" + jsonObject1.getString("catId"));
                                modelCategory.setTitle("" + jsonObject1.getString("catName"));

                                modelCategories.add(modelCategory);

                            }

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


                        if (getIntent().hasExtra("update")){

                            for (int j = 0; j < modelCategories.size(); j++) {

                                if (catId.equalsIgnoreCase("" + modelCategories.get(j).getId())) {
                                    if (strings != null) {
                                        strings.add(0, modelCategories.get(j).getTitle());
                                        ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_item, strings);
                                        stringArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                                        spinner.setAdapter(stringArrayAdapter);
                                    }

                                }

                            }
                    }else{


                            ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_item, strings);
                            stringArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            spinner.setAdapter(stringArrayAdapter);


                        }
                    }

                    @Override
                    public void onError(ANError anError) {
                        ProjectUtils.pauseProgressDialog();


                    }
                });


    }

    void apiCreate(){



        AndroidNetworking.upload(Consts.Status.BASE_URL + Consts.Status.GET_CREATE_ITEM_VENDOR)
                .addMultipartParameter("UserId",""+userId)
                .addMultipartParameter("ItemName",""+etName.getText().toString())
                .addMultipartParameter("ItemCategoryId",""+catId)
                .addMultipartParameter("ItemStock",""+quantity.getText().toString())
                .addMultipartParameter("ItemStockUnit",""+unit)
                .addMultipartParameter("ItemStockWeight",""+weight.getText().toString())
                .addMultipartParameter("ItemRate",""+etRate.getText().toString())
                .addMultipartParameter("itemMRP",""+etRateMRP.getText().toString())
                .addMultipartFile("ItemImage",file)
                .setPriority(Priority.IMMEDIATE)
                .setTag(Consts.Status.SEARCH_API)
                .build()
                .getAsString(new StringRequestListener() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jsonObject=new JSONObject(response);
                            if(jsonObject.getString("status").equals("1")){
                                Toast.makeText(mContext,"Item added successfully.",Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(mContext,"Try Again",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

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

                    }
                });
    }


    void apiUpdateCreate(){



        AndroidNetworking.upload(Consts.Status.BASE_URL + Consts.Status.GET_CREATE_ITEM_VENDOR)
                .addMultipartParameter("UserId",""+userId)
                .addMultipartParameter("ItemName",""+etName.getText().toString())
                .addMultipartParameter("ItemCategoryId",""+catId)
                .addMultipartParameter("ItemStock",""+quantity.getText().toString())
                .addMultipartParameter("ItemStockUnit",""+unit)
                .addMultipartParameter("ItemStockWeight",""+weight.getText().toString())
                .addMultipartParameter("ItemRate",""+etRate.getText().toString())
                .addMultipartParameter("itemMRP",""+etRateMRP.getText().toString())
                .addMultipartParameter("ItemId",""+itemId)
                .addMultipartFile("ItemImage",file)

                .setPriority(Priority.IMMEDIATE)
                .setTag(Consts.Status.SEARCH_API)
                .build()
                .getAsString(new StringRequestListener() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jsonObject=new JSONObject(response);
                            if(jsonObject.getString("status").equals("1")){
                                Toast.makeText(mContext,"Item updated successful.",Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(mContext,"Try Again",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void onError(ANError anError){
                        Toast.makeText(mContext,"something went wrong!",Toast.LENGTH_SHORT).show();
                    }
                });
    }
    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);

        ((Activity) mContext).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 "";
    }




    @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);

                    imageSave.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);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String pathImage = saveImage(Objects.requireNonNull(bitmap));
            file = new File(pathImage);

            imageSave.setImageBitmap(bitmap);


        }

    }
    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();

                        }

                        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();

    }

    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.selectImg:
                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;
            case R.id.addItems:
                if(etName.getText().toString().isEmpty()){
                    etName.setError("Enter Item name here!");
                    etName.requestFocus();


                }else{
                    if(unit.isEmpty()){
                        Toast.makeText(mContext,"Select item Unit!",Toast.LENGTH_SHORT).show();

                    }else{

                        if(quantity.getText().toString().isEmpty()){
                            quantity.setError("Enter Stock Quantity Available in store!");
                            quantity.requestFocus();

                        }else{

                                if(catId.isEmpty()){
                                    Toast.makeText(mContext,"Select Category Please!",Toast.LENGTH_SHORT).show();
                                }else{
                                    if(tag.equalsIgnoreCase("update")){
                                        apiUpdateCreate();

                                    }else{
                                        if(etRate.getText().toString().isEmpty()){
                                            etRate.setError("Enter Rate of item!");
                                            etRate.requestFocus();

                                        }else {
                                            apiCreate();
                                        }}
                                }



                        }}


                }
                break;
        }
    }
}
