package ir.almahdi.sandogh_bsa_aza;

import android.app.AutomaticZenRule;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import ir.almahdi.sandogh_bsa_aza.Add_OtherOzv_pay.Add_OtherOzv_payment;
import ir.almahdi.sandogh_bsa_aza.Class.MySingleton;
import ir.almahdi.sandogh_bsa_aza.Sepordeh_ozv.frag_view_mosh_karbar;
import ir.almahdi.sandogh_bsa_aza.Tarakonesh_ozv.tarako_karbar_frg;
import ir.almahdi.sandogh_bsa_aza.setting.sal_mali.frg_set_sabt_vam;
import ir.almahdi.sandogh_bsa_aza.setting.sal_mali.frg_sett_sal_mali;
import ir.almahdi.sandogh_bsa_aza.vam_ha_ozv.model.md_vam_karbar;
import ir.almahdi.sandogh_bsa_aza.vam_ha_ozv.vam_karbar_frg;
import ir.almahdi.sandogh_bsa_aza.vam_other_ozv.vam_other_frg;

public class karbar_activity extends AppCompatActivity {
    public AutomaticZenRule img_nvg_setting;
    BottomNavigationView bottomNavigationView;
     ImageView  img_menu_nvg,img_hadith, imgSelection,img_user;
    NavigationView nvgView_setting;
    TextView img_par_ozviat;
    vam_karbar_frg vam_ozv;
    FrameLayout fram_vam_ozv,fram_asli,fram_vam_other;
  CheckBox chkBox_vam;
    final frag_view_mosh_karbar fragViewMoshKarbar =  frag_view_mosh_karbar.newInstance();
    SharedPreferences shPref;
    TextView idname_fam, idozv, idsalozv, idmoj,idmab_hagh_oz_emsal;
    private RecyclerView recyclerView;
    final Fragment frgVam=new vam_karbar_frg();
    //a list to store all the products
    private List<md_vam_karbar> myVamList = new ArrayList<>();

    @Override
        protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_karbar_activity);
        img_menu_nvg=findViewById(R.id.img_nvg_setting);
// تعاریف فریم های لایوت اصلی
            fram_vam_ozv=findViewById(R.id.fram_vam_ozv);
            fram_vam_ozv.setVisibility(View.VISIBLE);
            fram_asli=findViewById(R.id.fram_asli);
            fram_vam_other=findViewById(R.id.fram_vam_other);
            //پایات فریم

           // img_par_ozviat=findViewById(R.id.img_par_ozviat);
        // تعاریف ویوهای برنامه
        chkBox_vam=findViewById(R.id.chkSelected);
        bottomNavigationView = findViewById(R.id.bottom_nav);
        //منوی تنظیمات
        img_hadith = findViewById(R.id.img_hadith);
        nvgView_setting=findViewById(R.id.nvg_setting);
        if (Global_var.gid_ozviat.equals("860027") || Global_var.gid_ozviat.equals("860074")){
            img_menu_nvg.setVisibility(View.VISIBLE);
        }
        else{
            img_menu_nvg.setVisibility(View.GONE);

        }
            img_menu_nvg.setOnClickListener(v -> {
                if (nvgView_setting.getVisibility()==View.VISIBLE){
                    nvgView_setting.setVisibility(View.GONE);
                    }
                else{ nvgView_setting.setVisibility(View.VISIBLE);
                    nvgView_setting.showContextMenu();
                    }
                nvgView_setting.setNavigationItemSelectedListener(item -> {
                    switch (item.getItemId()) {

                        case R.id.item_salmali:
                         //   FragmentManager fm=getSupportFragmentManager();
                            DialogFragment frg_set_sal_mali=new frg_sett_sal_mali();
                            frg_set_sal_mali.showNow(getSupportFragmentManager(),"show frg_salmali");
                            nvgView_setting.setVisibility(View.GONE);
                            return true;
                        case R.id.item_sabt_vam:
                            DialogFragment frg_sbt_vam=new frg_set_sabt_vam();
                            frg_sbt_vam.showNow(getSupportFragmentManager(),"show frg_sabt_vam");
                            nvgView_setting.setVisibility(View.GONE);
                            return true;
                        case R.id.item_3:
//                            imgSelection.setVisibility(View.INVISIBLE);


//                        vp_karbar.setCurrentItem(2);

                            return true;
                        case R.id.item_4:

                            return true;
                        case R.id.item_5:
                            fram_vam_ozv.setVisibility(View.INVISIBLE);
                            fram_vam_other.setVisibility(View.INVISIBLE);

                            Fragment frgTarako=new tarako_karbar_frg();
                            getSupportFragmentManager().beginTransaction()
                                    .replace(R.id.fram_asli,frgTarako)
                                    .commit();
                            nvgView_setting.setVisibility(View.GONE);
                            return true;
                            case R.id.item_6:

                            return true;
                        case R.id.item_7:
                            // finish();
                            finishAffinity(); // Close all activites
                            System.exit(0);
                            return true;
                    }
                    return true;});

            });
        // پر کردن مشخصات عضو
           senddata();
// پایان پر کردن مشخصات عضو
            Toast.makeText(getApplicationContext(),getResources().getString(R.string.txt_no_display_mos),Toast.LENGTH_LONG).show();
//        //مشخصات کاربر در منوی سپرده
        String salmali= Utility.getCurrentShamsidate().substring(2);
        Global_var.gsal_mali=salmali.substring(0,2);
//        //String sal_shamsi=currentShamsidate.substring(2,2);
      //  Toast.makeText(getApplicationContext(),currentShamsidate,Toast.LENGTH_LONG).show();
        idname_fam =findViewById(R.id.txt_nam_famil);
        idozv = findViewById(R.id.txt_numozv);
        idsalozv = findViewById(R.id.txt_salozv);
        idmoj = findViewById(R.id.txt_mojodi);
        idmab_hagh_oz_emsal=findViewById(R.id.mab_hagh_oz_emsal);
            //end مشخصات کاربر
        ///کد مربوط به مشخصات وام کاربر
            //getting the recyclerview from xml
            recyclerView = findViewById(R.id.recylcerview);
                      //پایان مشخصات وام

          //   اضافه کردن حق عضویت به سبد پرداخت
         //   img_par_ozviat=findViewById(R.id.img_par_ozviat);



        Glide
            .with(this)
            .load(R.raw.hadith)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
             .into(img_hadith);
            bottomNavigationView.setSelectedItemId(R.id.item_1);
        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {

            switch (item.getItemId()) {

                case R.id.item_1:
                                     //Toast.makeText(getApplicationContext(),currentShamsidate.substring(2,2),Toast.LENGTH_LONG).show();
                   // vam_ozv.get_vam_karbar();
                    fram_asli.setVisibility(View.VISIBLE);
                    fram_vam_ozv.setVisibility(View.VISIBLE);
                    fram_vam_other.setVisibility(View.INVISIBLE);
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.fram_asli,fragViewMoshKarbar)
                            .commit();
                    // set_mosh_karbar();
                    senddata();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.fram_vam_ozv,frgVam)
                            .commit();
                    return true;
                case R.id.item_2:
                    Global_var.sum_vam_other= 0L;
//                    imgSelection.setVisibility(View.INVISIBLE);
                    fram_asli.setVisibility(View.INVISIBLE);
                    fram_vam_ozv.setVisibility(View.INVISIBLE);
                    fram_vam_other.setVisibility(View.VISIBLE);
//                        Fragment frg_vam_other=new vam_other_frg();
////                        getSupportFragmentManager().beginTransaction()
////                                .replace(R.id.fram_vam_other,frg_vam_other)
////                                .commit();
                    Global_var.sum_ozv_sabadpar=0;
                    myVamList.clear();
                    Global_var.numLoad_Vamozv=0;
                    for (byte i=0;i<10;i++){
                        Global_var.gkol_id_ozviat[i]="empty";
                    }
                    Global_var.num_array_gkol_id_ozviat=0;
                    Global_var.sum_vams_list_select_ozv= 0L;
                    Global_var.sum_pas_list_select_ozv=0L;
                    Global_var.sum_pas_vam_list_select_ozv=0L;
                    isDestroyed();
                    finish();
                        startActivity(new Intent(karbar_activity.this,Add_OtherOzv_payment.class));
                    //get_vam_karbar();
                    return true;
                case R.id.item_3:
//                    imgSelection.setVisibility(View.INVISIBLE);
                    fram_vam_ozv.setVisibility(View.INVISIBLE);
                    fram_vam_other.setVisibility(View.INVISIBLE);

                    Fragment frgTarako=new tarako_karbar_frg();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.fram_asli,frgTarako)
                            .commit();

//                        vp_karbar.setCurrentItem(2);

                    return true;
                case R.id.item_4:
                   // finish();
                    finishAffinity(); // Close all activites
                    System.exit(0);
                    return true;

                               }
            return true;});

}

    @Override
    public void onBackPressed() {
    }
    @Override
    public void onResume() {
        super.onResume();
        if( getIntent().getBooleanExtra("Exit me", false)){
            finish();
        System.exit(1);}

    }
    private void senddata()
    {
         final String url = "http://sandogh-bs.makkh.ir/seporde_karbar/read_mosh_ozv.php";
        final ProgressDialog progressDialog = new ProgressDialog(karbar_activity.this);

        Response.Listener<String> listener = new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response)
            {
                if ( Global_var.numLoad_Vamozv==0) {
                    progressDialog.show();
                    try {
                //   Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
                        JSONObject jsonObject = new JSONObject(response);
                        Global_var.gname_ozv = jsonObject.getString("name_ozv");
                        Global_var.glastname_ozv = jsonObject.getString("lastname_ozv");
                        // Global_var.gid_ozviat =jsonObject.getString("id_ozviat");
                        //Global_var.gtarikh_ejad =jsonObject.getString("tarikh_ejad");
                        Global_var.gmojodi_ozv = jsonObject.getString("mojodi_ozv");
                       // Global_var.gmojodi_ozv = mojozv.substring(0, mojozv.length() - 1);
                        Global_var.gmab_hagh_ozv = Long.valueOf(jsonObject.getString("mab_hagh_ozv"));
                      //  Global_var.gmab_hagh_ozv = Long.valueOf(mhozv.substring(0, mhozv.length() - 1));
                        Global_var.gtarikh_ozviat = jsonObject.getString("tarikh_ozviat");

//                                fragmentManager.beginTransaction().replace(R.id.fragment_container_view_tag, frag_view_mosh_karbar).commit();
//                                Toast.makeText(getApplicationContext(), response.getString("lastname_ozv"), Toast.LENGTH_LONG).show();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //   Toast.makeText(getApplicationContext(), Global_var.gname_ozv +" "+ Global_var.glastname_ozv, Toast.LENGTH_LONG).show();
                    progressDialog.dismiss();

                }else{progressDialog.dismiss();}
            }

        };

        Response.ErrorListener errorListener = new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                Toast.makeText(karbar_activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
        };

        StringRequest request = new StringRequest(Request.Method.POST, url, listener, errorListener)
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError
            {
                Map<String, String> map = new Hashtable<>();
                map.put("id_ozviat",Global_var.gid_ozviat);
                map.put("sal_mali",Global_var.gsal_mali);

                return map;
            }
        };

        MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
    }



//    public void img_par_hozv(View view) {
//        //Toast.makeText(getApplicationContext(), String.valueOf(Global_var.mablagh_pard_ozv), Toast.LENGTH_LONG).show();
//        if(Global_var.num_click_pay_ozv==0){
//        Global_var.sum_hozv_vam_ozv = (int) ((Global_var.mablagh_pard_ozv)+Long.parseLong( Global_var.gmab_hagh_ozv));
//        Toast.makeText(getApplicationContext(), "حق عضویت به سبد پرداخت اضافه شد", Toast.LENGTH_LONG).show();
//      //  Toast.makeText(getApplicationContext(), String.valueOf(Global_var.mablagh_pard_ozv), Toast.LENGTH_LONG).show();
//       Global_var.num_click_pay_ozv+=1;
//        }
//        else{
//            Toast.makeText(getApplicationContext(), "شما حق عضویت به سبد پرداخت اضافه کرده اید!", Toast.LENGTH_LONG).show();
//        }
//        }


        public void btn_add_karb_pard(View view) {
        Fragment frgother_vam=new vam_other_frg();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fram_asli,frgother_vam)
                    .addToBackStack(null)
                    .commit();
    }
    //     @RequiresApi(api = Build.VERSION_CODES.N)
//     public void img_par_ozviat(View view) {
//
//        Global_var.mablagh_pard_ozv= Math.toIntExact(Long.parseLong(Global_var.mablagh_pard_ozv + Global_var.gmab_hagh_ozv));
//        Toast.makeText(getApplicationContext(), "حق عضویت به سبد پرداخت اضافه شد", Toast.LENGTH_LONG).show();
//         //img_par_ozviat.setVisibility(View.INVISIBLE);
//    }

//    public void imp_par_zarin(View view) {
//                 img_pay= view.findViewById(R.id.img_pard_ghest);
//            Intent intent = new Intent(getApplicationContext(), zarinpal.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//            startActivity(intent);
//
//    }
}

//    @SuppressLint("SetTextI18n")
//    private void set_mosh_karbar() {
//        idozv.setText(Global_var.gid_ozviat);
//        idname_fam.setText(Global_var.gname_ozv+" "+Global_var.glastname_ozv);
//        idmab_hagh_oz_emsal.setText(Global_var.gmab_hagh_ozv);
//        idmoj.setText(Global_var.gmojodi_ozv);
//        idsalozv.setText(Global_var.gtarikh_ozviat);
//
//    }

;

/*
 * Copyright (c) 2018 Faruk Ahmed
 * License Under MIT
 * Not use for commercial perpose
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 */




//        // Post Request For JSONObject
//        public void postData() {
//            final ProgressDialog progressDialog = new ProgressDialog(karbar_activity.this);
//            progressDialog.setMessage("در حال دریافت اطلاعات");
//            progressDialog.setCancelable(false);
//            progressDialog.show();
//
//            final String url = "http://sandogh-bs.makkh.ir/test_user.php";
//            JSONObject object = new JSONObject();
//            try {
//                //input your API parameters
//
//                object.put("id_ozviat",Global_var.gid_ozviat);
//                object.put("tarikh_ejad",Global_var.gsal_mali);
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//            // Enter the correct url for your api service site
//
//            StringRequest request = new StringRequest(Request.Method.POST, url,
//                    new Response.Listener<String>() {
//                        @Override
//                        public void onResponse(String response) {
//
//                            try {
//                                Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
//                                JSONObject jsonObject=new JSONObject(response);
//                                Global_var.gname_ozv =jsonObject.getString("name_ozv");
//                                Global_var.glastname_ozv =jsonObject.getString("lastname_ozv");
//                               Global_var.gid_ozviat =jsonObject.getString("id_ozviat");
//                                //Global_var.gtarikh_ejad =jsonObject.getString("tarikh_ejad");
//                                Global_var.gmojodi_ozv =jsonObject.getString("mojodi_ozv");
//                                Global_var.gmab_hagh_ozv = jsonObject.getString("mab_hagh_ozv");
//                                Global_var.gtarikh_ozviat = jsonObject.getString("tarikh_ozviat");
////                                fragmentManager.beginTransaction().replace(R.id.fragment_container_view_tag, frag_view_mosh_karbar).commit();
////                                Toast.makeText(getApplicationContext(), response.getString("lastname_ozv"), Toast.LENGTH_LONG).show();
//
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                         //   Toast.makeText(getApplicationContext(), Global_var.gname_ozv +" "+ Global_var.glastname_ozv, Toast.LENGTH_LONG).show();
//                            progressDialog.dismiss();
//
//                        }
//                                // String vazeyat_ozv1=new String(json.getString("vazeyat_ozv").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//                                }, new Response.ErrorListener() {
//                @Override
//                public void onErrorResponse(VolleyError error) {
//                    error.printStackTrace();
//                    progressDialog.dismiss();
//                }
//
//
//
//
//                public Map<String, String> getParams() throws AuthFailureError
//                {
//                    Map<String, String> map = new Hashtable<>();
//                    map.put("id_ozviat",Global_var.gid_ozviat);
//                    map.put("tarikh_ejad",Global_var.gsal_mali);
//
//                    return map;
//                }
//            });
//           // requestQueue.add(jsonObjectRequest);
//            MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
//
//        }
//       private void configViewPager(ViewPager viewPager) {
//
//       ViewpagerAdapter adapter = new ViewpagerAdapter(getSupportFragmentManager());
//
//        frag_view_mosh_karbar sepordeh_Frg = new frag_view_mosh_karbar();
//        OtherAza_Select_frg        vam_frag = new OtherAza_Select_frg();
//        tarako_karbar_frg     trak_frag = new tarako_karbar_frg();
//
//         adapter.addToList(sepordeh_Frg, "sep");
//         adapter.addToList(vam_frag, "vam");
//         adapter.addToList(trak_frag, "tarako");
//
//        viewPager.setAdapter(adapter);
//    }

//    static class ViewpagerAdapter extends FragmentPagerAdapter {
//
//        List<Fragment> myFragmentsList = new ArrayList<>();
//        List<String> myPageTitlesList = new ArrayList<>();
//
//        public ViewpagerAdapter(FragmentManager fm) {
//            super(fm);
//        }
//
//        @Override
//        public Fragment getItem(int position) {
//            return myFragmentsList.get(position);
//        }
//
//        @Override
//        public int getCount() {
//            return myFragmentsList.size();
//        }
//
//        @Override
//        public CharSequence getPageTitle(int position) {
//            return myPageTitlesList.get(position);
//        }
//
//        public void addToList(Fragment fragment, String title){
//
//            myFragmentsList.add(fragment);
//            myPageTitlesList.add(title);
//        }
//    }
//ارسال و دریافت با جیسون اری
/*
Map<String, String> params = new HashMap<>();
params.put("ID", id);
params.put("USER_ID", userId);
MyJsonArrayRequest jsonArrayRequest = new MyJsonArrayRequest(GET_JSON_DATA_HTTP_URL, params,

    new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

            progressBar.setVisibility(View.GONE);

            //ffتابع گرفتن پاسخ از سرور
            JSON_PARSE_DATA_AFTER_WEBCALL(response);
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    پایان درخواست
    البته صف درخواست ایجاد نکردیم(mysinglton)
    */
/*
کد کامل تابع درخواست چند تا فیلد و جواب جیسون اری و قرار دادن در رسایکلر ویو
باید این تابع در کلیک منو ها فراخوانی کنیم- میتونیم یک ورودی به تابع بدیم که
شماره عضویت بگیره و به سرور ارسال کنه
public void JSON_DATA_WEB_CALL(){
      String uid ="value"//Or you can use your value to pass

      StringRequest strrequest = new StringRequest(Request.Method.POST,GET_JSON_DATA_HTTP_URL,

              new Response.Listener<String>() {
                  @Override
                  public void onResponse(String response) {

                      progressBar.setVisibility(View.GONE);
                      try {
                          JSON_PARSE_DATA_AFTER_WEBCALL(response);
                      } catch (JSONException e) {
                          e.printStackTrace();
                      }

                  }
              },
              new Response.ErrorListener() {
                  @Override
                  public void onErrorResponse(VolleyError error) {

                  }
              }){
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {
              Map<String, String> params = new HashMap<>();
              params.put("userid", uid);//userid to send to php
              return params;
          }
      };

      requestQueue = Volley.newRequestQueue(this);

      requestQueue.add(strrequest);
  }

  public void JSON_PARSE_DATA_AFTER_WEBCALL(String array) throws JSONException {

      JSONArray jarr = new JSONArray(array);
      for(int i = 0; i<jarr.length(); i++) {
          GetDataAdapter GetDataAdapter2 = new GetDataAdapter();//adapter class
          //JSONObject json;
          try {
              JSONObject json = jarr.getJSONObject(i);
             // JSONObject json = (JSONObject) array.get(String.valueOf(i));

              //set and get methods should declare here with database colmun names and json names
              GetDataAdapter2.setcontact_fname(json.getString(JSON_FNAME));
              GetDataAdapter2.setcontact_lname(json.getString(JSON_LNAME));

          } catch (JSONException e) {

              e.printStackTrace();
          }
          GetDataAdapter1.add(GetDataAdapter2);

      }

      recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
      recyclerView.setAdapter(recyclerViewadapter);
  }
}
 */
