package org.deke.risk.riskahead.fragment;

import androidx.annotation.NonNull;
import androidx.fragment.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.toolbox.StringRequest;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.api.defaults.DefaultBootstrapBrand;
import com.google.firebase.crashlytics.FirebaseCrashlytics;

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(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile_stats, container, false);
        parent = (ProfileActivity)getActivity();

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

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

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

        Bundle arguments = getArguments();
        if(arguments != null){
            uid = getArguments().getString("uid",parent.user.get(SessionManager.KEY_UID));
            getProfileStatsForList();
        }else{
            FirebaseCrashlytics.getInstance().log("Could not retrieve arguments");
        }

        return view;
    }

    private void getProfileStatsForList() {
        ProfileActivity activity = (ProfileActivity) getActivity();
        if(activity != null){
            activity.showDialog();

            StringRequest strReq = getStringRequestProfileStats();
            String tag_string_req = "req_profilestats";
            AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
        }else{
            FirebaseCrashlytics.getInstance().log("Could not retrieve activity for ProfileStats");
        }
    }

    private StringRequest getStringRequestProfileStats() {
        return new StringRequest(Request.Method.POST,  AppConfig.REST_GET_USERSTATS, response -> {
            Log.d(TAG, "User stats: " + response);

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (!error && isAdded()) {
                    posts.setText(jObj.getString("numberOfPosts"));

                    JSONObject subJObj = jObj.getJSONObject("msg");
                    points.setText(subJObj.getString("points"));
                    ranking.setText(subJObj.getString("rank"));
                    txtMemberSince.setText(subJObj.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{
                        boolean no_ads = false;
                        boolean premium = false;

                        for(int i = 0; i < jSubs.length();i++) {
                            if(jSubs.getJSONObject(i).getString("productId").contains("no_ads")){
                                no_ads = true;
                            }
                            if(jSubs.getJSONObject(i).getString("productId").contains("extra_functions")){
                                premium = true;
                            }
                        }

                        ProfileActivity activity = (ProfileActivity) getActivity();
                        if(activity != null){
                            if(no_ads){
                                btnMembershipType.setBootstrapBrand(DefaultBootstrapBrand.PRIMARY);
                                btnMembershipType.setText(getResources().getString(R.string.lbl_membershiptype_addfree));
                                activity.session.setSubsNoAds(true);
                            }else{
                                activity.session.setSubsNoAds(false);
                            }

                            if(premium){
                                btnMembershipType.setBootstrapBrand(DefaultBootstrapBrand.WARNING);
                                btnMembershipType.setText(getResources().getString(R.string.lbl_membershiptype_premium));
                                activity.session.setSubsPremium(true);
                            }else{
                                activity.session.setSubsPremium(false);
                            }
                        }else{
                            FirebaseCrashlytics.getInstance().log("Could not retrieve activity for ProfileStatistics. Could not set statusLevel");
                        }
                    }

                    if(!parent.user.get(SessionManager.KEY_UID).equals(uid)  ){
                        lblPoints.setText(String.format("%s %s", 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(String.format("%s %s",jObj.getString("username"), getResources().getString(R.string.lbl_profile_membersince_someone)));
                    }
                } else {
                    String errorMsg = jObj.getString("error_msg");
                    FirebaseCrashlytics.getInstance().log("Error getting user stats (server returned error): " + errorMsg);

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

                ((ProfileActivity)getActivity()).hideDialog();
            } catch (JSONException e) {
                FirebaseCrashlytics.getInstance().log("JSONException caught");
                FirebaseCrashlytics.getInstance().recordException(e);
            }
        }, error -> {
            FirebaseCrashlytics.getInstance().log("Error getting user stats: " + error.getMessage());
            ProfileActivity activity = (ProfileActivity) getActivity();
            if(activity != null){
                activity.hideDialog();
                activity.handleVolleyErrorResponse();
            }else {
                FirebaseCrashlytics.getInstance().log("Could not retrieve activity for onErrorResponse");
            }
        }) {

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

                return params;
            }
        };
    }

}
