package com.kuulchatmedia.closeapp.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.kuulchatmedia.closeapp.R;
import com.kuulchatmedia.closeapp.activity.MainActivity;
import com.kuulchatmedia.closeapp.other.AdapterSearchResult;
import com.kuulchatmedia.closeapp.other.BusinessCategoryRecyclerViewAdapter;
import com.kuulchatmedia.closeapp.other.Functions;
import com.kuulchatmedia.closeapp.other.HorizontalReclerviewItem;
import com.kuulchatmedia.closeapp.other.OfferCateryData;
import com.kuulchatmedia.closeapp.other.SQLiteHandler;
import com.kuulchatmedia.closeapp.other.ServerHorizontalRecyclerviewItem;
import com.kuulchatmedia.closeapp.other.SessionManager;
import com.kuulchatmedia.closeapp.other.StaticReclerviewItemAdapter;

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

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link HomeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private RecyclerView horizontal_offer_recycler_view;
    private ArrayList<HorizontalReclerviewItem> horizontal_offer_List;
    private StaticReclerviewItemAdapter horizontal_offer_Adapter;
    private RecyclerView horizontal_contact_recycler_view;
    private ArrayList<ServerHorizontalRecyclerviewItem> horizontal_contact_List;
    private BusinessCategoryRecyclerViewAdapter horizontal_contact_Adapter;
    private ProgressBar bar;
    private SessionManager session;
    private String sessionToken;
    private SQLiteHandler db;
    private Functions f;

    private OnFragmentInteractionListener mListener;

    public HomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        //Load the Recyclerview conent for the business category

        // SQLite database handler
        db = new SQLiteHandler(getActivity());
        // Session manager
        session = new SessionManager(getActivity());

        f = new Functions();

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(getContext(), MainActivity.class);
            startActivity(intent);
            getActivity().finish();
        }
        HashMap<String, String> user = db.getSession();

        // Staff session token
        sessionToken = user.get("session");

        bar = (ProgressBar)view.findViewById(R.id.progressBar);
        bar.setVisibility(View.VISIBLE);
        //Initialize the views
        horizontal_contact_recycler_view= (RecyclerView) view.findViewById(R.id.categories);
        horizontal_contact_List = new ArrayList<ServerHorizontalRecyclerviewItem>();

        //Connect to the server to fetch categories
        new loadBusinessCategories().execute();


        //Load the Recyclerview content for the offer
        horizontal_offer_recycler_view= (RecyclerView) view.findViewById(R.id.offer_categories);
        horizontal_offer_List = new ArrayList<HorizontalReclerviewItem>();
        for (int i = 0; i < OfferCateryData.nameArray.length; i++) {
            horizontal_offer_List.add(new HorizontalReclerviewItem(
                    OfferCateryData.nameArray[i],
                    OfferCateryData.drawableArray[i]
            ));
        }
        horizontal_offer_Adapter=new StaticReclerviewItemAdapter(horizontal_offer_List);
        LinearLayoutManager horizontalLayoutManagaer
                = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        horizontal_offer_recycler_view.setLayoutManager(horizontalLayoutManagaer);
        horizontal_offer_recycler_view.setAdapter(horizontal_offer_Adapter);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    //Methods to load business categories
    private class loadBusinessCategories extends AsyncTask<String, Void, JSONObject> {
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected JSONObject doInBackground(String... params) {
            //Connet to the server to fetch json data
            JSONObject json = f.business_categories(sessionToken);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            bar.setVisibility(View.GONE);
            try {
                if(!(json==null)) {
                    JSONArray jArray = json.getJSONArray("categories");;
                    // Extract data from json and store into ArrayList as class objects
                    // Clear the old data in the data
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject json_data = jArray.getJSONObject(i);

                        // Set the searchresult object
                        String name = f.decrypt(json_data.getString("name"));
                        String image = f.decrypt(json_data.getString("image"));
                        String id    = f.decrypt(json_data.getString("id"));

                        ServerHorizontalRecyclerviewItem result = new ServerHorizontalRecyclerviewItem(name,image,id);
                        horizontal_contact_List.add(result);
                    }

                    horizontal_contact_Adapter=new BusinessCategoryRecyclerViewAdapter(getContext(),horizontal_contact_List);
                    LinearLayoutManager horizontalLayoutManagaer
                            = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
                    horizontal_contact_recycler_view.setLayoutManager(horizontalLayoutManagaer);
                    horizontal_contact_recycler_view.setAdapter(horizontal_contact_Adapter);

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

    }
}
