package in.techware.carrefour.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import in.techware.carrefour.R;
import in.techware.carrefour.model.UserBean;
import in.techware.carrefour.model.UserListBean;
import in.techware.carrefour.util.AppConstants;
import in.techware.carrefour.util.menuUtils.DropDownMenuUtil;

public class AuthenticateActivity extends BaseAppCompatNoDrawerActivity {

    private Button btnBack;
    private Button btnOK;
    private EditText etxtUsername;
    private EditText etxtPassword;
    private UserListBean userListBean;
    private View.OnClickListener clickListener;
    private boolean isSuperAdminRequired = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_authenticate);

        if (getIntent() != null && getIntent().hasExtra("isSuperAdminRequired")) {
            isSuperAdminRequired = getIntent().getBooleanExtra("isSuperAdminRequired", false);
        }

        initViews();

        handleKeyboard();

        populateViewModel();

        if (getSupportActionBar() != null) {
            setTitle(R.string.title_credential, R.color.white);
            getSupportActionBar().setTitle("");
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(true);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQ_FILE_TRANSFER && resultCode == RESULT_OK) {
            if (data != null && data.hasExtra("result")) {
                if (data.getIntExtra("result", 0) == AppConstants.FILE_TRANSFER_RESULT_SEND_DATA_COMPLETED) {
                    finish();
                }
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();

        if (userListBean == null || userListBean.getUserList().isEmpty()) {
            setProgressScreenVisibility(true, true);
            getData(false);
        } else {
            getData(true);
        }

    }

    private void getData(boolean isSwipeRefreshing) {
        swipeView.setRefreshing(isSwipeRefreshing);
        userListBean = DropDownMenuUtil.getUserList();
        setProgressScreenVisibility(false, false);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_base, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                toolbar.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
                //                mVibrator.vibrate(25);
                onAuthenticateBackClick(toolbar);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initViews() {

        etxtUsername = findViewById(R.id.etxt_authenticate_username);
        etxtPassword = findViewById(R.id.etxt_authenticate_password);

        btnBack = findViewById(R.id.btn_authenticate_back);
        btnOK = findViewById(R.id.btn_authenticate_ok);

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onAuthenticateBackClick(v);
            }
        });

        btnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onAuthenticateOKClick(v);
            }
        });

        etxtPassword.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    if (etxtPassword.getText().toString().length() > 0) {
                        btnOK.requestFocus();
                    }
                    return true; // consume.
                }
                return false; // pass on to other listeners.
            }
        });
        etxtUsername.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    if (etxtUsername.getText().toString().length() > 0) {
                        etxtPassword.requestFocus();
                    }
                    return true; // consume.
                }
                return false; // pass on to other listeners.
            }
        });
    }

    private void handleKeyboard() {

        if (getSharedPreferences(AppConstants.PREF_FILE, 0).getBoolean(AppConstants.KEYBOARD_STATUS, false)) {
            etxtPassword.setFocusableInTouchMode(true);
            etxtUsername.setFocusableInTouchMode(true);
        } else {
//            etxtSection.setOnFocusChangeListener(focusChangedListener);
//            etxtPassword.setOnFocusChangeListener(focusChangedListener);
//            etxtUsername.setOnFocusChangeListener(focusChangedListener);
            etxtPassword.setFocusableInTouchMode(false);
            etxtUsername.setFocusableInTouchMode(false);
            setClickListener(etxtPassword);
            setClickListener(etxtUsername);
        }
    }

    private void setClickListener(final EditText etxt) {
        clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etxt.setEnabled(true);
                etxt.setTextIsSelectable(true);
                etxt.setFocusable(true);
                etxt.setFocusableInTouchMode(true);

                if (etxt.isEnabled() && !etxt.hasFocus()) {
                    etxt.requestFocus();
                }

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        };
    }

    private void populateViewModel() {

        etxtUsername.setFocusable(true);
        etxtUsername.setEnabled(true);

        enableViews(true);

    }

    private void enableViews(boolean isEnable) {
        etxtUsername.setEnabled(isEnable);
        etxtPassword.setEnabled(isEnable);

        etxtUsername.setFocusable(isEnable);
        etxtPassword.setFocusable(isEnable);

        etxtPassword.setTextIsSelectable(isEnable);
        etxtPassword.setFocusableInTouchMode(isEnable);
        etxtUsername.setTextIsSelectable(isEnable);
        etxtUsername.setFocusableInTouchMode(isEnable);
    }

    public void onAuthenticateBackClick(View view) {
        view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        //mVibrator.vibrate(25);

        Intent intent = new Intent();
        intent.putExtra("result", AppConstants.AUTHENTICATION_RESULT_CANCELLED);
        setResult(RESULT_OK, intent);
        finish();
    }

    public void onAuthenticateOKClick(View view) {
        view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        //mVibrator.vibrate(25);

        String username = etxtUsername.getText().toString();
        String password = etxtPassword.getText().toString();
        if (username.equals("")) {
            Snackbar.make(coordinatorLayout, R.string.message_address_is_required, Snackbar.LENGTH_LONG)
                    .setAction(R.string.btn_dismiss, snackBarDismissOnClickListener).show();
        } else if (password.equals("")) {
            Snackbar.make(coordinatorLayout, R.string.message_password_is_required, Snackbar.LENGTH_LONG)
                    .setAction(R.string.btn_dismiss, snackBarDismissOnClickListener).show();
        } else {
            if (userListBean != null && !userListBean.getUserList().isEmpty()) {

                UserBean userBean = userListBean.authenticate(username, password);
                if (userBean != null) {

                    if (!isSuperAdminRequired || userBean.isSuperAdmin()) {
                        Intent intent = new Intent();
                        intent.putExtra("result", AppConstants.AUTHENTICATION_RESULT_SUCCESS);
                        intent.putExtra("userBean", userBean);
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        Snackbar.make(coordinatorLayout,
                                R.string.message_you_need_to_be_a_super_admin_to_continue, Snackbar.LENGTH_LONG)
                                .setAction(R.string.btn_dismiss, snackBarDismissOnClickListener).show();
                    }
                } else {
                    Snackbar.make(coordinatorLayout, R.string.message_user_does_not_exist, Snackbar.LENGTH_LONG)
                            .setAction(R.string.btn_dismiss, snackBarDismissOnClickListener).show();
                }
            } else {
                Snackbar.make(coordinatorLayout, R.string.message_user_does_not_exist, Snackbar.LENGTH_LONG)
                        .setAction(R.string.btn_dismiss, snackBarDismissOnClickListener).show();
            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onAuthenticateBackClick(toolbar);
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_MENU) {
            openOptionsMenu();
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            // TODO: 22-07-2018 Do Things On Enter Click
            Toast.makeText(this, "EnterClicked", Toast.LENGTH_SHORT).show();
            return false;
        }
        return false;
    }
}
