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.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.UserApi;
import com.androiddev.project.ili.wishurgift.application.Wishurgift;
import com.androiddev.project.ili.wishurgift.model.User;
import com.google.gson.Gson;

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

/**
 * Created by Ouahab FENNICHE on 13/04/2020
 */
public class EditProfilFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private int idUser;
    private TextView newName, newEmail;
    CheckBox newVisibility;
    Button saveNewProfil, cancelEditAccount;
    private Gson gson = new Gson();
    private ProgressDialog pg;


    public EditProfilFragment() {

    }

    public static EditProfilFragment newInstance(int idUser) {
        EditProfilFragment fragment = new EditProfilFragment();
        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));
        }
        View view = inflater.inflate(R.layout.edit_account_information, container, false);
        newName = view.findViewById(R.id.newName);
        newEmail = view.findViewById(R.id.newEmail);
        newVisibility = view.findViewById(R.id.new_profil_chkpublic);
        saveNewProfil = view.findViewById(R.id.saveNewProfil);
        saveNewProfil.setOnClickListener(v -> saveChangeInfo());
        cancelEditAccount = view.findViewById(R.id.cancelEditAccount);
        cancelEditAccount.setOnClickListener(v -> exitEditAccount());

        return view;
    }


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

    /**
     * Function to update account info (name, email, public or not)
     */

    private void saveChangeInfo() {
        UserApi.updateUser(newName.getText().toString(), newEmail.getText().toString(), null, newVisibility.isChecked(), response -> afficherProfilInfo(), error -> {
            onError();
        });
    }

    private void afficherProfilInfo() {
        onPreExecute();
        UserApi.getUserProfile(idUser, (Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                User usr = gson.fromJson(jsonObject.getJSONObject("data").toString(), User.class);
                newName.setText(usr.getUserName());
                newEmail.setText(usr.getEmail());
                newVisibility.setChecked(usr.getPublic());
                pg.dismiss();
                showProfil();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> {
            onError();
        });

    }

    public void exitEditAccount() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
        alertDialogBuilder.setTitle("Confirm exit");
        alertDialogBuilder.setMessage("Are you sure you want to exit");
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setPositiveButton("Yes", (arg0, arg1) -> showProfil());
        alertDialogBuilder.setNegativeButton("No", (dialog, which) -> dialog.cancel());
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }


    private void showProfil() {
        ((AppMainActivity) getActivity()).afficherProfil(idUser);

    }

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

