package com.pixelnx.localhelp.ui.vendor;

import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;

import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
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.pixelnx.localhelp.R;
import com.pixelnx.localhelp.model.ModelShopListData;
import com.pixelnx.localhelp.model.ModelUserData;
import com.pixelnx.localhelp.spash.Database;
import com.pixelnx.localhelp.spash.Modellogo;
import com.pixelnx.localhelp.ui.base.ActivityBase;
import com.pixelnx.localhelp.ui.order.ActivityOrderCart;
import com.pixelnx.localhelp.ui.user.ActivityProfileSetting;
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.CustomTextBold;

import com.squareup.picasso.Picasso;

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

import java.util.ArrayList;

public class ActivityAllStore extends ActivityBase implements View.OnClickListener {
Context mContext;
    RecyclerView rvShopList;
    ArrayList<ModelShopListData.Data> shopsList;
    ImageView profileIv;
    ImageView sideDrawer;
    ImageView shopIv;
    CustomTextBold title;
    CustomEditText etSearch;
    ListView drawerListView;
    CardView rvOrderRes;
    SharedPref sharedPref;
    ModelUserData modelUserData;
    ImageView ivUserImage;
    Database database;
    Modellogo modellogo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentBaseView(R.layout.fragment_home);
        mContext=ActivityAllStore.this;
        drawerLayout = findViewById(R.id.drawerLayout);
        profileIv=findViewById(R.id.profileIv);
        drawerListView = findViewById(R.id.drawerListView);
        drawerListView.bringToFront();
        drawerLayout.requestLayout();
        profileIv.setOnClickListener(this);
        title = findViewById(R.id.Heading);
        try {
            PackageInfo pInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            int verCode = pInfo.versionCode;

            version(verCode);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        database = Room.databaseBuilder
                (getApplicationContext(),
                        Database.class, "database-name").fallbackToDestructiveMigration()
                .allowMainThreadQueries().build();
        modellogo=new Modellogo();
        modellogo= database.daoAccess().getAllSetData();
        if(!modellogo.getLogoTitle().isEmpty()){
            title.setText(""+modellogo.getLogoTitle());}
        ivUserImage = findViewById(R.id.ivUserImage);
        shopIv = findViewById(R.id.shopIv);
        rvOrderRes = findViewById(R.id.rvorderRes);
        rvOrderRes.setVisibility(View.GONE);
        sharedPref = SharedPref.getInstance(mContext);
        modelUserData = sharedPref.getUser(Consts.Status.SP);
        sideDrawer = findViewById(R.id.sideDrawer);
        sideDrawer.setOnClickListener(this);
        etSearch = findViewById(R.id.etSearch);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {



                    searchItem(s.toString());


            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });
        etSearch.setOnClickListener(this);
        shopIv.setOnClickListener(this);
        rvShopList=findViewById(R.id.rvShopList);
        rvShopList.setLayoutManager(new LinearLayoutManager(mContext));
            ProjectUtils.showProgressDialog(mContext, false, "Loading...");

        AndroidNetworking.post(Consts.Status.BASE_URL + Consts.Status.GET_VENDORES_API)
                .addBodyParameter(Consts.Status.START,""+0)
                .addBodyParameter(Consts.Status.LIMIT,""+100)
                .setPriority(Priority.IMMEDIATE)
                .setTag(Consts.Status.SEARCH_API)
                .build()
                .getAsObject(ModelShopListData.class, new ParsedRequestListener<ModelShopListData>() {
                    @Override
                    public void onResponse(ModelShopListData response) {

                        if(response.getStatus().contains("1")){
                        shopsList=new ArrayList<>();


                        AdapterShop adapterFragmentShop=new AdapterShop(mContext,response.getUserData());
                        rvShopList.setAdapter(adapterFragmentShop);}else{
                            Toast.makeText(mContext,"No store found!!",Toast.LENGTH_SHORT).show();

                        }

                        ProjectUtils.pauseProgressDialog();
                    }

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

                    }
                });

    }

    @Override
    protected void onResume() {
        super.onResume();
        Picasso.get()
                .load(Consts.Status.BASE_IMAGE_URL+"users/" + modelUserData.getData().getUserImage())
                .placeholder(R.drawable.noimage)
                .into(ivUserImage);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sideDrawer:
                drawerLayout.openDrawer(Gravity.LEFT);
                Picasso.get()
                        .load(Consts.Status.BASE_IMAGE_URL+"users/" + modelUserData.getData().getUserImage())
                        .placeholder(R.drawable.noimage)
                        .into(ivUserImage);
                break;
            case R.id.shopIv:
                Intent intentShop=new Intent(mContext, ActivityOrderCart.class);
                startActivity(intentShop);
                break;
            case R.id.profileIv:
                Intent intent=new Intent(mContext, ActivityProfileSetting.class);
                startActivity(intent);
                break;

        }
    }
    void version(final int versionCode) {
        AndroidNetworking.post(Consts.Status.BASE_URL + Consts.Status.GET_APP_VERSION_API)
                .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").contains("1")) {
                                int apiCode= Integer.parseInt(jsonObject.getString("version"));
                                if(versionCode != apiCode){

                                    openAppUpdateDialog();

                                }


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


                    }

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

    }
    private void openAppUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setCancelable(false);
        builder.setMessage("Please update your app you are using older version")
                .setCancelable(false)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        final String appPackageName = getPackageName();
                        try {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                        } catch (android.content.ActivityNotFoundException anfe) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
                        }
                    }
                });

        AlertDialog alert = builder.create();
        alert.show();

    }
    void searchItem(String string){


        AndroidNetworking.post(Consts.Status.BASE_URL + Consts.Status.GET_VENDORES_API)
                .addBodyParameter(Consts.Status.START,""+0)
                .addBodyParameter(Consts.Status.LIMIT,""+100)
                .addBodyParameter("vendorName",""+string)
                .setPriority(Priority.IMMEDIATE)
                .setTag(Consts.Status.SEARCH_API)
                .build()
                .getAsObject(ModelShopListData.class, new ParsedRequestListener<ModelShopListData>() {
                    @Override
                    public void onResponse(ModelShopListData response) {

                        if(response.getStatus().contains("1")){
                        shopsList=new ArrayList<>();

                        AdapterShop adapterFragmentShop=new AdapterShop(mContext,response.getUserData());
                        rvShopList.setAdapter(adapterFragmentShop);}else{
                            shopsList=new ArrayList<>();

                            ProjectUtils.pauseProgressDialog();
                            AdapterShop adapterFragmentShop=new AdapterShop(mContext,shopsList);
                            rvShopList.setAdapter(adapterFragmentShop);
                            Toast.makeText(mContext,"No store found!!",Toast.LENGTH_SHORT).show();
                        }
                        ProjectUtils.pauseProgressDialog();
                    }

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

                    }
                });



    }

    @Override
    public void onBackPressed() {

        exitAppDialog();
    }

    private void exitAppDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("HOME DELIVERY APP");
        builder.setMessage("Are you sure you want to close this app?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

}
