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 android.widget.Toast;

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.ContactsApi;
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;

/**
 * Created by Ouahab FENNICHE on 26/04/2020
 */
public class ShowContactDetails extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private TextView name1, email, tag2, statsContact;
    private CheckBox checkPublic;
    private ImageView imgContact;
    private Gson gson = new Gson();
    private int contactParent;
    private ProgressDialog pg;

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

    public static ShowContactDetails newInstance(int param1) {
        ShowContactDetails contactDetails = new ShowContactDetails();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        contactDetails.setArguments(args);
        return contactDetails;

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            contactParent = 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));
        }
        View view = inflater.inflate(R.layout.fragment_detailscontact, container, false);
        name1 = view.findViewById(R.id.profil_nameinf_contact);
        email = view.findViewById(R.id.profil_email_contact);
        tag2 = view.findViewById(R.id.profil_tag2_contact);
        checkPublic = view.findViewById(R.id.profil_chkpublic_contact);
        imgContact = view.findViewById(R.id.profile_image_contact);
        afficherProfilContact();
        ImageView returnToProfil = view.findViewById(R.id.retrunToListContacts);
        returnToProfil.setOnClickListener(v -> ((AppMainActivity) getActivity()).afficherListesContacts());
        Button deletecontact = view.findViewById(R.id.deleteContact);
        deletecontact.setOnClickListener(v -> ContactsApi.deleteContact(contactParent, response -> {
            Toast.makeText(getContext(), "contact deleted", Toast.LENGTH_SHORT).show();
            ((AppMainActivity) getActivity()).afficherListesContacts();
        }, error -> {
            onError();
        }));
        statsContact = view.findViewById(R.id.contactStats);
        afficherStatContact();

        return view;
    }

    private void afficherStatContact() {
        StatsApi.getStatsById(contactParent, (Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                ContactStats contactStats = gson.fromJson(jsonObject.getJSONObject("data").toString(), ContactStats.class);

                statsContact.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());
        pg.setTitle("Processing...");
        pg.setMessage("Please wait.");
        pg.setCancelable(false);
        pg.setIndeterminate(true);
        pg.show();
    }

    private void afficherProfilContact() {
        onPreExecute();
        UserApi.getUserProfile(contactParent, (Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                User usr = gson.fromJson(jsonObject.getJSONObject("data").toString(), User.class);
                name1.setText(usr.getUserName());
                email.setText(usr.getEmail());
                tag2.setText(usr.getTag());
                checkPublic.setChecked(usr.getPublic());
                Glide.with(getContext()).load(usr.getAvatar()).into(imgContact);

                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();
    }
}

