package com.androiddev.project.ili.wishurgift.fragments;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.android.volley.Response;
import com.androiddev.project.ili.wishurgift.R;
import com.androiddev.project.ili.wishurgift.activities.AppMainActivity;
import com.androiddev.project.ili.wishurgift.activities.LoginActivity;
import com.androiddev.project.ili.wishurgift.api.StatsApi;
import com.androiddev.project.ili.wishurgift.api.UserApi;
import com.androiddev.project.ili.wishurgift.application.Wishurgift;
import com.androiddev.project.ili.wishurgift.model.ContactStats;
import com.androiddev.project.ili.wishurgift.model.User;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

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

public class ProfilFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private Gson gson = new Gson();
    private int idUser;
    private TextView name, name1, email, tag, tag2, myStats;
    CheckBox checkPublic;
    private ImageView imgavatar;
    Button updateProfil;
    private ProgressDialog pg;

    public ProfilFragment() {

    }

    public static ProfilFragment newInstance(int idUser) {
        ProfilFragment fragment = new ProfilFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, idUser);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            idUser = getArguments().getInt(ARG_PARAM1);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(Wishurgift.getSessionVariables().getUserConnected()==null || Wishurgift.getSessionVariables().getToken()==null){
            getActivity().finish();
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
        final View view = inflater.inflate(R.layout.fragment_show_profil, container, false);
        name = view.findViewById(R.id.profil_name);
        name1 = view.findViewById(R.id.profil_nameinf);
        email = view.findViewById(R.id.profil_email);
        tag = view.findViewById(R.id.profil_tag);
        tag2 = view.findViewById(R.id.profil_tag2);
        checkPublic = view.findViewById(R.id.profil_chkpublic);
        imgavatar = view.findViewById(R.id.profile_image);
        afficherProfil();
        updateProfil = view.findViewById(R.id.updateProfil);
        updateProfil.setOnClickListener(v -> ((AppMainActivity) getActivity()).updateProfil(idUser));

        myStats = view.findViewById(R.id.myStats);
        afficherMyStat();
        return view;
    }

    private void afficherMyStat() {

        StatsApi.getStatsById(idUser, (Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                ContactStats contactStats = gson.fromJson(jsonObject.getJSONObject("data").toString(), ContactStats.class);
                myStats.setText("number of Wishlist : " + contactStats.getNbWishlist() + "\n Number of elements : " + contactStats.getNbElement() +
                        "\n Number of contacts : " + contactStats.getNbContact() + "\n idea : " + contactStats.getNbIdea() +
                        " crush : " + contactStats.getNbCrush() + " , reserved : " + contactStats.getNbReserved() +
                        "\n purchased : " + contactStats.getNbPurchased() + " , Average price : " + contactStats.getNbAveragePrice() +
                        "\n Lowest price : " + contactStats.getNbLowestPrice() + " , Highest price : " + contactStats.getNbHighestPrice());

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> {
            onError();
        });

    }

    protected void onPreExecute() {
        pg = new ProgressDialog(getContext(), R.style.AppTheme_Dark_Dialog);
        pg.setTitle("Processing...");
        pg.setMessage("Please wait.");
        pg.setCancelable(false);
        pg.setIndeterminate(true);
        pg.show();
    }

    public void afficherProfil() {
        onPreExecute();
        UserApi.getUserProfile(idUser, (Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                User usr = gson.fromJson(jsonObject.getJSONObject("data").toString(), User.class);
                name.setText(usr.getUserName());
                name1.setText(usr.getUserName());
                email.setText(usr.getEmail());
                tag.setText(usr.getTag());
                tag2.setText(usr.getTag());
                checkPublic.setChecked(usr.getPublic());
                Glide.with(getContext()).load(usr.getAvatar()).into(imgavatar);
                pg.dismiss();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> {
            onError();
        });
    }

    public void onError(){
        AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(getContext());
        alertDialogBuilder.setTitle("An error has occured");
        alertDialogBuilder.setMessage("You will be redirected to the login page").setCancelable(false).setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                Wishurgift.getSessionVariables().setUserConnected(null);
                Wishurgift.getSessionVariables().setToken(null);
                ((AppMainActivity)getActivity()).finish();
                getActivity().startActivity(new Intent(getContext(), LoginActivity.class));
            }
        });
        AlertDialog alertDialog =alertDialogBuilder.create();
        alertDialog.show();
    }

}

