package de.sebse.fuplanner.fragments;

import android.app.ProgressDialog;
import android.content.Context;
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 java.io.IOException;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import de.sebse.fuplanner.MainActivity;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.GoogleAuth.GoogleAuth;
import de.sebse.fuplanner.services.KVV.KVV;
import de.sebse.fuplanner.services.KVV.types.LoginToken;
import de.sebse.fuplanner.services.KVV.types.Modules;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.logging.Logger;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link LoginFragment.OnLoginFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link LoginFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LoginFragment extends Fragment {
    private OnLoginFragmentInteractionListener mListener;
    private final Logger log = new Logger(this);
    private MainActivityListener mActivityListener;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment LoginFragment.
     */
    public static LoginFragment newInstance() {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_login, container, false);
        try {
            Context context = getContext();
            if (context != null) {
                Modules modules = Modules.load(context);
                if (modules != null) {
                    Button offline_btn = v.findViewById(R.id.btn_offline);
                    offline_btn.setVisibility(View.VISIBLE);
                    offline_btn.setText(v.getResources().getString(R.string.enter_offline_mode, modules.getToken().getUsername()));
                    offline_btn.setOnClickListener(v1 -> mListener.onLoginFragmentInteraction(modules.getToken(), false));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        View btn_login = v.findViewById(R.id.btn_login);
        btn_login.setOnClickListener(view -> {
            final ProgressDialog progressDialog = new ProgressDialog(LoginFragment.this.getContext(),
                    R.style.FUTheme_Dialog);
            progressDialog.setIndeterminate(true);
            progressDialog.setMessage("Authenticating...");
            progressDialog.show();

            EditText input_usr = ((View) view.getParent()).findViewById(R.id.input_username);
            EditText input_pwd = ((View) view.getParent()).findViewById(R.id.input_password);
            if (input_usr != null) {
                if (input_pwd != null) {
                    if (LoginFragment.this.getActivity() == null) {
                        log.e("Login fragment has no activity!");
                        return;
                    }
                    String username = input_usr.getText().toString();
                    String password = input_pwd.getText().toString();
                    KVV kvv = ((MainActivity) getActivity()).getKVV();
                    GoogleAuth gauth = ((MainActivity) getActivity()).getGoogleAuth();
                    kvv.login(username, password, success -> {
                        progressDialog.dismiss();
                        gauth.setLoginState(username, password);
                        if (mListener != null) {
                            input_usr.setError(null);
                            input_pwd.setError(null);
                            mListener.onLoginFragmentInteraction(success, true);
                        }
                    }, error -> {
                        progressDialog.dismiss();
                        // Invalid password
                        if (mActivityListener != null) {
                            if (error.getCode() == 100131) {
                                mActivityListener.showToast(R.string.invalid_credentials);
                                input_usr.setError(input_usr.getResources().getString(R.string.invalid_credentials));
                                input_pwd.setError(input_pwd.getResources().getString(R.string.invalid_credentials));
                            } else {
                                mActivityListener.showToast(v.getResources().getString(R.string.error_occurred_code, error.getCode()));
                            }
                        }
                        log.e("Error on KVV login!", error);
                    });
                }
            }
        });

        return v;
    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnLoginFragmentInteractionListener) {
            mListener = (OnLoginFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnLoginFragmentInteractionListener");
        }
        if (context instanceof MainActivityListener) {
            mActivityListener = (MainActivityListener) context;
            mActivityListener.onTitleTextChange(R.string.log_in);
        } else
            throw new RuntimeException(context.toString() + " must implement MainActivityListener");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnLoginFragmentInteractionListener {
        void onLoginFragmentInteraction(LoginToken loginToken, boolean onlineMode);
    }
}
