package org.deke.risk.riskahead.fragment;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.api.defaults.DefaultBootstrapBrand;

import org.deke.risk.riskahead.ProfileActivity;
import org.deke.risk.riskahead.R;
import org.deke.risk.riskahead.helper.AppConfig;
import org.deke.risk.riskahead.helper.AppController;
import org.deke.risk.riskahead.helper.SessionManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 *
 * (C) Copyright 2016 RiskAhead (http://www.riskahead.net)
 * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net)
 * Date of Release: 10.02.2016
 *
 */
public class ProfileStatisticsFragment extends Fragment {

    private final static String TAG = ProfileStatisticsFragment.class.getSimpleName();

    private ProfileActivity parent;
    private String uid = "";

    private TextView points ;
    private TextView ranking ;
    private TextView posts ;
    private  TextView txtMemberSince ;

    private TextView lblPoints;
    private  TextView lblPosts;
    private TextView lblRanking;
    private TextView lblMemberSince;

    private BootstrapButton btnMembershipType;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile_stats, container, false);
        parent = (ProfileActivity)getActivity();

        points =  (TextView) view.findViewById(R.id.txt_profile_points);
        ranking =  (TextView) view.findViewById(R.id.txt_profile_ranking);
        posts =  (TextView) view.findViewById(R.id.txt_profile_numberposts);
        txtMemberSince = (TextView) view.findViewById(R.id.txt_profile_membersince);

        lblPoints =  (TextView) view.findViewById(R.id.lbl_profile_points);
        lblRanking =  (TextView) view.findViewById(R.id.lbl_profile_ranking);
        lblPosts =  (TextView) view.findViewById(R.id.lbl_profile_numberposts);
        lblMemberSince = (TextView) view.findViewById(R.id.lbl_profile_membersince);

        btnMembershipType = (BootstrapButton) view.findViewById(R.id.btn_profile_membershiptype);

        uid = getArguments().getString("uid",parent.user.get(SessionManager.KEY_UID));

        getProfileStatsForList();

        return view;
    }

    private void getProfileStatsForList() {
        ((ProfileActivity)getActivity()).showDialog();

        StringRequest strReq = getStringRequestProfileStats();
        String tag_string_req = "req_profilestats";
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private StringRequest getStringRequestProfileStats() {
        return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "User stats: " + response);

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {
                        jObj = jObj.getJSONObject("msg");
                        points.setText(jObj.getString("points"));
                        ranking.setText(jObj.getString("rank"));
                        posts.setText(jObj.getString("numberOfPosts"));
                        txtMemberSince.setText(jObj.getString("created_at"));

                        JSONArray jSubs = jObj.getJSONArray("subs");

                        if(jSubs.length() == 0){
                            btnMembershipType.setBootstrapBrand(DefaultBootstrapBrand.SUCCESS);
                            btnMembershipType.setText(getResources().getString(R.string.lbl_membershiptype_free));
                        }else{
                            for(int i = 0; i < jSubs.length();i++) {
                                if(jSubs.getJSONObject(i).getString("productId").contains("no_ads")){
                                    btnMembershipType.setBootstrapBrand(DefaultBootstrapBrand.PRIMARY);
                                    btnMembershipType.setText(getResources().getString(R.string.lbl_membershiptype_addfree));
                                    ((ProfileActivity) getActivity()).session.setSubsNoAds(true);
                                }else{
                                    ((ProfileActivity) getActivity()).session.setSubsNoAds(false);
                                }

                                if(jSubs.getJSONObject(i).getString("productId").contains("extra_functions")){
                                    btnMembershipType.setBootstrapBrand(DefaultBootstrapBrand.WARNING);
                                    btnMembershipType.setText(getResources().getString(R.string.lbl_membershiptype_premium));
                                    ((ProfileActivity) getActivity()).session.setSubsPremium(true);
                                }else{
                                    ((ProfileActivity) getActivity()).session.setSubsPremium(false);
                                }
                            }
                        }

                        if(!parent.user.get(SessionManager.KEY_UID).equals(uid)  ){
                            lblPoints.setText(jObj.getString("username")+" "+getResources().getString(R.string.lbl_profile_points_someone));
                            lblPosts.setText(getResources().getString(R.string.lbl_profile_numofposts_me));
                            lblRanking.setText(getResources().getString(R.string.lbl_profile_ranking_someone));
                            lblMemberSince.setText(jObj.getString("username")+" "+getResources().getString(R.string.lbl_profile_membersince_someone));
                        }
                    } else {
                        String errorMsg = jObj.getString("error_msg");
                        Log.e(TAG, "Error getting user stats (server returned error): " + errorMsg);

                        parent.showMessage(getResources().getString(R.string.txt_errormsg_retrievestats));
                    }

                    ((ProfileActivity)getActivity()).hideDialog();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error getting user stats: " + error.getMessage());
                ((ProfileActivity)getActivity()).hideDialog();
                ((ProfileActivity)getActivity()).handleVolleyErrorResponse();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("tag", AppConfig.REST_GET_USERSTATS);
                params.put("uid", parent.user.get(SessionManager.KEY_UID));
                params.put("token", parent.user.get(SessionManager.TOKEN));
                params.put("userstatsid", uid);

                return params;
            }
        };
    }

}
