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.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
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 2020-02-03
 */
public class SettingsFragment extends Fragment {

    private Button btnUpdatePassword, btnChangeColorAppli, btnYellow, btnPink, btnGreen, btnRed, btnBlue, btnGrey;
    private Switch modeNight;

    private Gson gson = new Gson();


    private View popupInputDialogView = null;
    private EditText oldPassword = null;
    private EditText newPassword = null;

    private Button saveNewPassword = null;
    private Button applyChangeColor = null;
    private Button cancelChangePassword = null;
    private Button logout;

    private ProgressDialog pg;


    public static final String MyPREFERENCES = "nightModePrefs";
    public static final String KEY_ISNIGHTMODE = "isNightMode";


    public SettingsFragment() {
    }

    public static SettingsFragment newInstance() {
        SettingsFragment fragment = new SettingsFragment();
        return fragment;
    }

    @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.settings_fragment, container, false);
        btnUpdatePassword = view.findViewById(R.id.btnUpdatePassword);
        btnUpdatePassword.setOnClickListener(v -> changePasswordPopup());
        btnChangeColorAppli = view.findViewById(R.id.colorappli);
        btnChangeColorAppli.setOnClickListener(v -> changeColorPopup());
        modeNight = view.findViewById(R.id.switchMode);
        modeNight.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                Toast.makeText(getContext(), "Mode night yes", Toast.LENGTH_SHORT).show();
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);

            } else {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

            }
        });
        logout = view.findViewById(R.id.logout);
        logout.setOnClickListener(v -> logout());
        return view;
    }


    private void logout() {
        Wishurgift.getSessionVariables().setUserConnected(null);
        Wishurgift.getSessionVariables().setToken(null);
        getActivity().finish();
        startActivity(new Intent(getActivity(), LoginActivity.class));
    }



    public void changePasswordPopup() {

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
        alertDialogBuilder.setTitle("Change Password Dialog");
        alertDialogBuilder.setIcon(R.drawable.ic_launcher_background);
        alertDialogBuilder.setCancelable(false);
        initPopupViewControls();
        alertDialogBuilder.setView(popupInputDialogView);
        final AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

        saveNewPassword.setOnClickListener(view -> {
            saveChangePasswordAccount();
            alertDialog.cancel();
        });
        cancelChangePassword.setOnClickListener(view -> alertDialog.cancel());
    }

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

    /**
     * Update Only Password
     */
    private void saveChangePasswordAccount() {
        onPreExecute();

        UserApi.updateUser(null, null, newPassword.getText().toString(), false, response -> {
            pg.dismiss();
            afficherProfilInfo();
        }, error -> onError2());

    }

    private void afficherProfilInfo() {
        onPreExecute();
        UserApi.getUserProfile(Wishurgift.getSessionVariables().getUserConnected().getId(), (Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                User usr = gson.fromJson(jsonObject.getJSONObject("data").toString(), User.class);
                newPassword.setText(usr.getPassword());
                pg.dismiss();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> {
            onError();
        });

    }

    /* Initialize popup dialog view and ui controls in the popup dialog. */
    private void initPopupViewControls() {
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        popupInputDialogView = layoutInflater.inflate(R.layout.popup_change_password_dialog, null);
        oldPassword = popupInputDialogView.findViewById(R.id.oldpassword_popup);
        newPassword = popupInputDialogView.findViewById(R.id.newpassword_popup);
        saveNewPassword = popupInputDialogView.findViewById(R.id.button_save_new_password);
        cancelChangePassword = popupInputDialogView.findViewById(R.id.button_cancel);

    }


    private void changeColorPopup() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
        alertDialogBuilder.setTitle("Change Color Application Dialog");
        alertDialogBuilder.setIcon(R.drawable.ic_launcher_background);
        alertDialogBuilder.setCancelable(false);
        initPopupViewControlsColors();
        alertDialogBuilder.setView(popupInputDialogView);
        final AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
        applyChangeColor.setOnClickListener(v -> alertDialog.cancel());


    }

    private void initPopupViewControlsColors() {

        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        popupInputDialogView = layoutInflater.inflate(R.layout.activity_colorful_actionbar, null);
        btnRed = popupInputDialogView.findViewById(R.id.btnred);
        btnRed.setOnClickListener(v -> {
            ((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorRed)));

        });

        btnYellow = popupInputDialogView.findViewById(R.id.btnyellow);
        btnYellow.setOnClickListener(v -> ((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorYellow))));

        btnPink = popupInputDialogView.findViewById(R.id.btnpink);
        btnPink.setOnClickListener(v -> ((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorPrimaryDark))));

        btnGreen = popupInputDialogView.findViewById(R.id.btngreen);
        btnGreen.setOnClickListener(v -> ((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorGreen))));

        btnRed = popupInputDialogView.findViewById(R.id.btnred);
        btnRed.setOnClickListener(v -> ((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorRed))));

        btnGrey = popupInputDialogView.findViewById(R.id.btngrey);
        btnGrey.setOnClickListener(v -> ((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.grey))));


        btnBlue = popupInputDialogView.findViewById(R.id.btnblue);
        btnBlue.setOnClickListener(v -> ((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorBlue))));

        applyChangeColor = popupInputDialogView.findViewById(R.id.btnApplyChange);


    }

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

    public void onError2(){
        AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(getContext());
        alertDialogBuilder.setTitle("An error has occured");
        alertDialogBuilder.setMessage("Unable to change your password").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();
    }
}


