package org.keyscience.fragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.keyscience.BackgroundTask.LoginAsyncTask;
import org.keyscience.R;
import org.keyscience.SingletonPattern.SingletonFragmentList;
import org.keyscience.app.Constants;
import org.keyscience.app.HomeActivity;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;


public class LoginFragment extends Fragment {

    private boolean remember;

    private EditText usernameEntry;
    private EditText passwordEntry;

    private CheckBox rememberCheckBox;
    private Button loginButton;

    private Context context;

    private TextView registerText;
    private TextView lostPasswordText;

    private LinearLayout loadLinearLayout;
    private LinearLayout loginLinearLayout;

    private BroadcastReceiver loginSucessfulReceiver;
    private LoginAsyncTask loginAsyncTask;

    @Nullable
    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.login_layout, container, false);

        context = getContext();

        loadLinearLayout = view.findViewById(R.id.load_animation_login_linearLayout);
        loadLinearLayout.setVisibility(View.GONE);

        loginLinearLayout = view.findViewById(R.id.login_display);

        LinearLayout linearLayout = view.findViewById(R.id.loginLayout);

        Display display = (getActivity().getWindowManager().getDefaultDisplay());
        Point size = new Point();
        display.getSize(size);
        int height = size.y;
        linearLayout.setMinimumHeight(height - 180);

        usernameEntry = view.findViewById(R.id.username);
        passwordEntry = view.findViewById(R.id.password);

        registerText = view.findViewById(R.id.registerButton);
        registerText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.keyscience.org/wp-login.php?action=register"));
                context.startActivity(browserIntent);
            }
        });

        lostPasswordText = view.findViewById(R.id.lostPassButton);
        lostPasswordText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // This changes often on the WordPress end and should not be done programmatically.

                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.keyscience.org/wp-login.php?action=lostpassword"));
                context.startActivity(browserIntent);
            }
        });

        rememberCheckBox = view.findViewById(R.id.rememberCheckBox);
        rememberCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                                        @Override
                                                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                                            remember = isChecked;
                                                        }
                                                    }
        );

        loginButton = view.findViewById(R.id.loginButton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!usernameEntry.getText().toString().equals("") && !passwordEntry.getText().toString().equals("")) {
                    loadLinearLayout.setVisibility(View.VISIBLE);
                    loginLinearLayout.setVisibility(View.GONE);

                    //send user and password to remote db for validation
                    loginAsyncTask = new LoginAsyncTask(remember, getContext());
                    loginAsyncTask.execute(usernameEntry.getText().toString(), passwordEntry.getText().toString());

                } else
                    Toast.makeText(context, "Missing required fields, please try again.", Toast.LENGTH_SHORT).show();
            }
        });

        // upon successful login, this broadcast receiver will launch EcoQuest
        loginSucessfulReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Constants.ACTION_LOGIN)) {
                    loadLinearLayout.setVisibility(View.GONE);
                    passwordEntry.setText("");
                    loginLinearLayout.setVisibility(View.VISIBLE);
                    ((HomeActivity) getActivity()).setViewPager(SingletonFragmentList.getInstance().getFragmentPosition(Constants.PROFILE));

                } else if (intent.getAction().equals(Constants.FAILED_LOGIN)) {
                    loadLinearLayout.setVisibility(View.GONE);
                    loginLinearLayout.setVisibility(View.VISIBLE);
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.ACTION_LOGIN);
        filter.addAction(Constants.FAILED_LOGIN);
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(loginSucessfulReceiver, filter);

        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (loginAsyncTask != null) {
            loginAsyncTask.cancel(true);
            try {
                //Waits if necessary to complete
                loginAsyncTask.get();
            } catch (ExecutionException e) {
                //  ignore
            } catch (InterruptedException e) {
                //  ignore
            } catch (CancellationException e) {
                //  ignore
            }
            loginAsyncTask = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(loginSucessfulReceiver);
    }
}
