package com.pixelnx.sam.jobportal.Fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.pixelnx.sam.jobportal.Activity.FilterActivity;
import com.pixelnx.sam.jobportal.Activity.SeekerDashboardActivity;
import com.pixelnx.sam.jobportal.Adapter.AdapterDashboard;
import com.pixelnx.sam.jobportal.DTO.ActiveJobDTO;
import com.pixelnx.sam.jobportal.DTO.DummyFilterDTO;
import com.pixelnx.sam.jobportal.DTO.UserSeekerDTO;
import com.pixelnx.sam.jobportal.DTOCI.AllJobs;
import com.pixelnx.sam.jobportal.DTOCI.ModelLanguageDTO;
import com.pixelnx.sam.jobportal.DTOCI.ModelSeekerLogin;
import com.pixelnx.sam.jobportal.R;
import com.pixelnx.sam.jobportal.network.NetworkManager;
import com.pixelnx.sam.jobportal.preferences.SharedPrefrence;
import com.pixelnx.sam.jobportal.utils.AppConstans;
import com.pixelnx.sam.jobportal.utils.AppRater;
import com.pixelnx.sam.jobportal.utils.Consts;
import com.pixelnx.sam.jobportal.utils.CustomEdittext;
import com.pixelnx.sam.jobportal.utils.ProjectUtils;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class SeekerHomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private LinearLayout llIcon;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerview = null;
    private AdapterDashboard adapterDashboard;
    private ActiveJobDTO activeJobDTO;
    private ArrayList<AllJobs.Data> dataArrayList;
    private ArrayList<AllJobs.Data> appliedDataArrayList;

    private LinearLayoutManager linearLayoutManagerVertical;
    private ArrayList<String> process = new ArrayList<>();
    View view;
    private SharedPrefrence prefrence;
    private ModelSeekerLogin userSeekerDTO;
    private SeekerDashboardActivity seekerDashboardActivity;
    private LinearLayout searchLayout;
    private CustomEdittext etSearch;
    private ImageView ivSearch;
    InputMethodManager inputManager;
    private String id = "";
    HashMap<Integer, ArrayList<DummyFilterDTO>> map;
    private ArrayList<DummyFilterDTO> dummyFilterList;
    private ImageView img;
    private AnimationDrawable anim;
    private ModelLanguageDTO.Data data;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home_fragment, container, false);
        inputManager = (InputMethodManager)
                getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        prefrence = SharedPrefrence.getInstance(getActivity());
        map = ProjectUtils.map;
        map.clear();
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
        recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
        searchLayout = (LinearLayout) view.findViewById(R.id.searchLayout);
        etSearch = (CustomEdittext) view.findViewById(R.id.etSearch);
        ivSearch = (ImageView) view.findViewById(R.id.ivSearch);
        llIcon = (LinearLayout) view.findViewById(R.id.llIcon);
        img = (ImageView) view.findViewById(R.id.img);
        data = prefrence.getLanguage(AppConstans.LANGUAGE).getData();
        if (prefrence.getBooleanValue(Consts.IS_REGISTER_SEEKER)) {
            userSeekerDTO = prefrence.getUserDTO(AppConstans.SEEKERDTO);
            id = userSeekerDTO.getData().getId();
        } else {
            id = "guest";
        }

        seekerDashboardActivity.tvJobs.setVisibility(View.VISIBLE);
        seekerDashboardActivity.tvJobs.setText(data.getMy_jobs1());
        seekerDashboardActivity.search_icon.setVisibility(View.VISIBLE);
        seekerDashboardActivity.filter_icon.setVisibility(View.VISIBLE);

        seekerDashboardActivity.search_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (searchLayout.getVisibility() == View.VISIBLE) {
                    etSearch.setText("");
                    inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    seekerDashboardActivity.search_icon.setImageResource(R.drawable.search);
                    searchLayout.setVisibility(View.GONE);
                    searchJobByKeyWord(etSearch.getText().toString());
                } else {
                    seekerDashboardActivity.search_icon.setImageResource(R.drawable.close);
                    etSearch.requestFocus();
                    inputManager.showSoftInput(etSearch, InputMethodManager.SHOW_IMPLICIT);
                    searchLayout.setVisibility(View.VISIBLE);
                }
            }
        });
        seekerDashboardActivity.filter_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), FilterActivity.class));
                map.clear();
            }
        });
        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                submitForm();
            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    submitForm();

                    return true;
                }
                return false;
            }
        });


        return view;
    }

    public void submitForm() {
        if (!validateSearch()) {
            return;
        } else {
            searchJobByKeyWord(etSearch.getText().toString());

        }
    }

    public boolean validateSearch() {
        if (etSearch.getText().toString().trim().length() <= 0) {
            etSearch.setError(data.getAll_field_required());
            etSearch.requestFocus();
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // AppRater.app_launched(getActivity());
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        searchJobByFilter();
                                        Log.e("Runnable", "FIRST");
                                        if (NetworkManager.isConnectToInternet(getActivity())) {
                                            swipeRefreshLayout.setRefreshing(false);
                                        } else {
                                            ProjectUtils.showToast(getActivity(), getResources().getString(R.string.internet_connection));
                                        }
                                    }
                                }
        );
    }

    private void searchJobByFilter() {
        Animation();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.SEARCH_BY_FILTER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {


                        try {
                            AllJobs jobs = new AllJobs();
                            jobs = new Gson().fromJson(response, AllJobs.class);
                            if (jobs.getStaus().equals("true")) {
                                dataArrayList = new ArrayList<>();
                                swipeRefreshLayout.setRefreshing(false);
                                dataArrayList = jobs.getData();
                                linearLayoutManagerVertical = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                                recyclerview.setLayoutManager(linearLayoutManagerVertical);

                                if (dataArrayList.size() != 0) {
                                    showAllAppliedJobs();

                                    final Handler handler = new Handler();
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            //Do something after 1s

                                            adapterDashboard = new AdapterDashboard(dataArrayList, getActivity());
                                            recyclerview.setAdapter(adapterDashboard);
                                            stopAnimation();
                                        }
                                    }, 500);

                                    recyclerview.setVisibility(View.VISIBLE);
                                    /*llIcon.setVisibility(View.GONE);*/
                                }

                            } else {
                                swipeRefreshLayout.setRefreshing(false);
                                ProjectUtils.showToast(getActivity(), jobs.getMessage());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            stopAnimation();
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.pauseProgressDialog();
                        swipeRefreshLayout.setRefreshing(false);
                        stopAnimation();
                        Log.d("ALL JOB RESPONSE", "Login Error:" + error);
                    }
                }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(AppConstans.KEYWORD, getUpdateJson());
                //   params.put(Consts.JOB_ID, jobApplicationDTOList.get(position).getId());
                Log.d("ALL ", "VALUE" + params);
                return params;
            }


        };
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);


    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        seekerDashboardActivity = (SeekerDashboardActivity) activity;
    }

    @Override
    public void onRefresh() {
        map.clear();
        showAllAvailableJobs();
    }

    private void showAllAvailableJobs() {
        Animation();
        StringRequest stringRequest = new StringRequest(Request.Method.GET, AppConstans.BASE_URL + AppConstans.ALL_JOB,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        ProjectUtils.pauseProgressDialog();

                        try {
                            AllJobs jobs = new AllJobs();
                            jobs = new Gson().fromJson(response, AllJobs.class);

                            if (jobs.getStaus().equals("true")) {
                                dataArrayList = new ArrayList<>();
                                swipeRefreshLayout.setRefreshing(false);
                                dataArrayList = jobs.getData();
                                linearLayoutManagerVertical = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                                recyclerview.setLayoutManager(linearLayoutManagerVertical);
                                recyclerview.setItemAnimator(new DefaultItemAnimator());
                                if (dataArrayList.size() != 0) {

                                    showAllAppliedJobs();

                                    final Handler handler = new Handler();
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            //Do something after 1s

                                            adapterDashboard = new AdapterDashboard(dataArrayList, getActivity());
                                            recyclerview.setAdapter(adapterDashboard);
                                            stopAnimation();
                                        }
                                    }, 500);

                                    recyclerview.setVisibility(View.VISIBLE);
                                    /*llIcon.setVisibility(View.GONE);*/
                                }

                            } else {
                                swipeRefreshLayout.setRefreshing(false);
                                ProjectUtils.showToast(getActivity(), jobs.getMessage());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            stopAnimation();
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.pauseProgressDialog();
                        swipeRefreshLayout.setRefreshing(false);
                        stopAnimation();
                        Log.d("ALL JOB RESPONSE", "Login Error:" + error);
                    }
                }) {

        };
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }

    public String getUpdateJson() {
        map = ProjectUtils.map;
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(Consts.SEEKER_ID, id);
            jsonObject.put(Consts.VALUE, ProjectUtils.getEditTextValue(etSearch));

            JSONArray job_type = new JSONArray();
            JSONArray job_location = new JSONArray();
            JSONArray specialization = new JSONArray();
            JSONArray qualification = new JSONArray();
            JSONArray job_by_roles = new JSONArray();
            JSONArray area_of_sector = new JSONArray();
            JSONArray experience = new JSONArray();
            if (!map.isEmpty()) {

                if (map.containsKey(0)) {
                    dummyFilterList = map.get(0);
                    jsonObject.put(Consts.JOB_TYPE, getJsonArray(dummyFilterList, 0));


                }
                if (map.containsKey(1)) {
                    dummyFilterList = map.get(1);
                    jsonObject.put(Consts.JOB_LOCATION, getJsonArray(dummyFilterList, 1));


                }
                if (map.containsKey(2)) {
                    dummyFilterList = map.get(2);
                    jsonObject.put(Consts.JOB_BY_ROLES, getJsonArray(dummyFilterList, 2));


                }

                if (map.containsKey(3)) {
                    dummyFilterList = map.get(3);
                    jsonObject.put(Consts.QUALIFICATION, getJsonArray(dummyFilterList, 3));


                }
                if (map.containsKey(4)) {
                    dummyFilterList = map.get(4);
                    jsonObject.put(Consts.EXPERIENCE, getJsonArray(dummyFilterList, 4));
                }
           /*     if (map.containsKey(5)) {
                    dummyFilterList = map.get(5);
                    jsonObject.put(Consts.SPECIALIZATION, getJsonArray(dummyFilterList,5));


                }


                if (map.containsKey(6)) {
                    dummyFilterList = map.get(6);
                    jsonObject.put(Consts.AREA_OF_SECTOR, getJsonArray(dummyFilterList,6));
                }*/
            } else {
                jsonObject.put(Consts.JOB_LOCATION, job_location);
                jsonObject.put(Consts.SPECIALIZATION, specialization);
                jsonObject.put(Consts.QUALIFICATION, qualification);
                jsonObject.put(Consts.JOB_BY_ROLES, job_by_roles);
                jsonObject.put(Consts.AREA_OF_SECTOR, area_of_sector);
                jsonObject.put(Consts.EXPERIENCE, experience);
                jsonObject.put(Consts.JOB_TYPE, job_type);
            }
            Log.e("update_json", jsonObject.toString());
            return jsonObject.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONObject().toString();
        }
    }

    public JSONArray getJsonArray(ArrayList<DummyFilterDTO> dummyList, int a) {
        JSONArray roleArray = new JSONArray();

        try {
            for (int i = 0; i < dummyList.size(); i++) {
                if (dummyList.get(i).isChecked()) {
                    String s = "";
                    if (a == 0) {
                        s = "_jt";
                    }

                    if (a == 1) {
                        s = "_loc";
                    }

                    if (a == 2) {
                        s = "_desi";
                    }
                    if (a == 3) {
                        s = "_qua";
                    }
                    if (a == 4) {
                        s = "_exp";
                    }

                    roleArray.put(dummyList.get(i).getName() + s);

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return roleArray;
    }


    public void showData() {

        if (map.containsKey(0)) {
            dummyFilterList = map.get(0);

        } else if (map.containsKey(1)) {
            dummyFilterList = map.get(1);


        } else if (map.containsKey(2)) {
            dummyFilterList = map.get(2);

        } else if (map.containsKey(3)) {
            dummyFilterList = map.get(3);


        } else if (map.containsKey(4)) {
            dummyFilterList = map.get(4);


        } else if (map.containsKey(5)) {
            dummyFilterList = map.get(5);


        } else if (map.containsKey(6)) {
            dummyFilterList = map.get(6);
        }
    }

    private void showAllAppliedJobs() {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.MY_APPLIED_JOB,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        ProjectUtils.pauseProgressDialog();
                        Log.e("ALL JOB RESPONSE", response.toString());
                        try {
                            AllJobs allJobs = new AllJobs();
                                allJobs = new Gson().fromJson(response, AllJobs.class);
                            appliedDataArrayList = new ArrayList<>();
                            if (allJobs.getStaus().equals("true")) {
                                appliedDataArrayList = allJobs.getData();
                                if (appliedDataArrayList.size() != 0) {
                                    for (int j = 0; j < dataArrayList.size(); j++) {
                                        for (int i = 0; i < appliedDataArrayList.size(); i++) {
                                            if (appliedDataArrayList.get(i).getId().equalsIgnoreCase(dataArrayList.get(j).getId())) {
                                                dataArrayList.get(j).setApplied(true);
                                            }
                                        }
                                    }
                                }
                                stopAnimation();
                            } else {

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.pauseProgressDialog();
                        // swipeRefreshLayout.setRefreshing(false);
                        Log.d("ALL JOB RESPONSE", "Login Error:" + error);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(AppConstans.EMAIL, prefrence.getUserDTO(AppConstans.SEEKERDTO).getData().getEmail());
                //   params.put(Consts.JOB_ID, jobApplicationDTOList.get(position).getId());

                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }

    private void searchJobByKeyWord(final String keyword) {
        ProjectUtils.showProgressDialog(getActivity(), true, "Searching Jobs..");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.SEARCH_BY_KEYWORD,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("ALL JOB RESPONSE", response.toString());
                        ProjectUtils.pauseProgressDialog();
                        try {
                            AllJobs jobs = new AllJobs();
                            jobs = new Gson().fromJson(response, AllJobs.class);
                            if (jobs.getStaus().equals("true")) {
                                dataArrayList = new ArrayList<>();
                                swipeRefreshLayout.setRefreshing(false);
                                dataArrayList = jobs.getData();
                                linearLayoutManagerVertical = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                                recyclerview.setLayoutManager(linearLayoutManagerVertical);
                                recyclerview.setItemAnimator(new DefaultItemAnimator());
                                if (dataArrayList.size() != 0) {
                                    recyclerview.setVisibility(View.VISIBLE);
                                    llIcon.setVisibility(View.GONE);
                                    adapterDashboard = new AdapterDashboard(dataArrayList, getActivity());
                                    recyclerview.setAdapter(adapterDashboard);
                                }
                            } else {
                                swipeRefreshLayout.setRefreshing(false);
                                ProjectUtils.showToast(getActivity(), new JSONObject(response).getString("message"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            swipeRefreshLayout.setRefreshing(false);
                            try {
                                ProjectUtils.showToast(getActivity(), new JSONObject(response).getString("message"));
                            } catch (Exception en) {
                                en.printStackTrace();
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.pauseProgressDialog();
                        swipeRefreshLayout.setRefreshing(false);
                        Log.d("ALL JOB RESPONSE", "Login Error:" + error);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                //  params.put(Consts.SEEKER_ID, userSeekerDTO.getData().getId());
                params.put(AppConstans.SEARCH_KEYWORD, keyword);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }

    private void Animation() {
        img.setVisibility(View.VISIBLE);
        anim = (AnimationDrawable) img.getDrawable();
        img.post(run);
    }

    Runnable run = new Runnable() {
        @Override
        public void run() {
            anim.start();
        }
    };

    private void stopAnimation() {
        anim.stop();
        img.setVisibility(View.GONE);
    }


}
