package kr.co.hanwha.hifive.screen.intro;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.firebase.analytics.FirebaseAnalytics;

import kr.co.hanwha.hifive.BuildConfig;
import kr.co.hanwha.hifive.HFApplication;
import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.admin.AdminInputDialog;
import kr.co.hanwha.hifive.admin.TestModeActivity;
import kr.co.hanwha.hifive.admin.admin.AdminModeActivity;
import kr.co.hanwha.hifive.admin.design.TestDesignActivity;
import kr.co.hanwha.hifive.base.BaseActivity;
import kr.co.hanwha.hifive.dialog.HFDefaultDialog;
import kr.co.hanwha.hifive.enums.BaseAnimationType;
import kr.co.hanwha.hifive.enums.BaseToolbarType;
import kr.co.hanwha.hifive.screen.intro.contract.IntroContract;
import kr.co.hanwha.hifive.util.HFCommonUtil;
import kr.co.hanwha.hifive.util.HFConstants;
import kr.co.hanwha.hifive.util.HFInfoUtil;
import kr.co.hanwha.hifive.view.HFDepartmentPickerView;
import kr.co.hanwha.hifive.view.HFLoginEditTextView;
import kr.co.hanwha.hifive.view.HFNumberKeypadView;
import kr.co.hanwha.hifive.view.HFPasswordEditTextView;

/**
 * SPLASH, 아이디 로그인, 간편 로그인 Presenter
 *
 * @see IntroPresenter
 * Created by sanghoonkwon on 2018. 1. 10..
 */

public class IntroActivity extends BaseActivity implements IntroContract.View {
    private HFPasswordEditTextView mPasswordEdit;
    private HFNumberKeypadView mNumberKeypadView;
    private TextView mTextViewAlertAccount;
    private TextView mTextViewAlertSimple;
    private LinearLayout mLayoutAccountLogin;
    private ScrollView mScrollView;
    private HFLoginEditTextView mLoginEditId;
    private HFLoginEditTextView mLoginEditPw;
    private LinearLayout mLayoutSimpleLogin;
    private ImageView mImageViewIcon;
    private TextView mTextViewRevision;
    private TextView mTextViewDepartment;
    private HFDepartmentPickerView mDepartmentPickerView;

    private GestureDetector mGestureDetector;
    private boolean mFocusId = false;
    private boolean mFocusPw = false;
    private final int DURATION_ICON = 500;

    private IntroContract.Presenter mPresenter;
    private FirebaseAnalytics mFirebaseAnalytics;

    @Override
    protected int getContentViewResource() {
        return R.layout.activity_intro;
    }

    @Override
    protected BaseToolbarType isToolbarStyle() {
        return BaseToolbarType.NONE;
    }

    @Override
    protected BaseAnimationType isShowActivityAnimation() {
        return null;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Obtain the FirebaseAnalytics instance.
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

        if (HFApplication.SERVER == HFApplication.SERVER_TYPE.DEV) {
            showToast("DEV SERVER!!!!!\n" + BuildConfig.DEV_URL);
        }

        mPasswordEdit = (HFPasswordEditTextView) findViewById(R.id.passwordEditText);
        mPasswordEdit.setOnInputPasswordListener(onInputPasswordListener);

        mNumberKeypadView = (HFNumberKeypadView) findViewById(R.id.numberKeypadView);
        mNumberKeypadView.setOnNumberKeypadListener(onNumberKeypadListener);

        mTextViewAlertSimple = (TextView) findViewById(R.id.alertSimple_textView);
        mTextViewAlertAccount = (TextView) findViewById(R.id.alertAccount_textView);

        mLayoutAccountLogin = (LinearLayout) findViewById(R.id.accountLogin_linearLayout);
        mScrollView = (ScrollView) findViewById(R.id.scrollView);
        mLoginEditId = (HFLoginEditTextView) findViewById(R.id.id_loginEditText);
        mLoginEditPw = (HFLoginEditTextView) findViewById(R.id.pw_loginEditText);
        mLoginEditId.setOnLoginEditTextListener(onLoginEditTextListener);
        mLoginEditPw.setOnLoginEditTextListener(onLoginEditTextListener);

        mLoginEditId.setEmailHint("@hanwha.com");

        mLayoutSimpleLogin = (LinearLayout) findViewById(R.id.simpleLogin_linearLayout);

        mGestureDetector = new GestureDetector(this, new MyGestureListener());
        mImageViewIcon = (ImageView) findViewById(R.id.icon_imageView);

        mLayoutAccountLogin.setVisibility(View.GONE);
        mLayoutSimpleLogin.setVisibility(View.GONE);

        findViewById(R.id.hidden_view).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mGestureDetector.onTouchEvent(event);
            }
        });

        mTextViewRevision = (TextView) findViewById(R.id.revision_textView);
        mTextViewRevision.setText(BuildConfig.REVISION);

        int screenHeight = HFCommonUtil.getScreenHeight(this);
        int largeWidth = HFCommonUtil.getPixelFromDimension(this, R.dimen.intro_icon_large_width);
        int targetY = (screenHeight - largeWidth) / 2;

        mImageViewIcon.setTranslationY(targetY);

        findViewById(R.id.department_linearLayout).setOnClickListener(onClickListener);
        findViewById(R.id.admin_view).setOnClickListener(onClickListener);
        findViewById(R.id.login_textView).setOnClickListener(onClickListener);
        findViewById(R.id.signup_textView).setOnClickListener(onClickListener);
        findViewById(R.id.resetPassword_textView).setOnClickListener(onClickListener);

        findViewById(R.id.login_textView).setEnabled(false);

        mTextViewDepartment = (TextView) findViewById(R.id.department_textView);
        String department = HFInfoUtil.getDepartmentText(this);
        mTextViewDepartment.setText(department);

        if (HFConstants.USER_TYPE_LF.equals(HFInfoUtil.getDepartmentValue(this)))
            findViewById(R.id.department_linearLayout).setVisibility(View.GONE);
        else
            findViewById(R.id.department_linearLayout).setVisibility(View.VISIBLE);

        mDepartmentPickerView = (HFDepartmentPickerView) findViewById(R.id.departmentPickerView);
        mDepartmentPickerView.setOnItemSelectedListener(onItemSelectedListener);

        mPresenter = new IntroPresenter(this);
        mPresenter.checkUpdate();
        mPresenter.checkLanding(getIntent());

        if (HFApplication.SERVER == HFApplication.SERVER_TYPE.REAL) {
            findViewById(R.id.hint_textView).setVisibility(View.GONE);
        } else {
            String url = "";
            if (HFApplication.SERVER == HFApplication.SERVER_TYPE.DEV)
                url = "API : " + BuildConfig.DEV_URL + "\n" +
                        "WEB : " + BuildConfig.WEB_DEV_URL;
            else if (HFApplication.SERVER == HFApplication.SERVER_TYPE.LOCAL)
                url = "API : " + BuildConfig.LOCAL_URL + "\n" +
                        "WEB : " + BuildConfig.WEB_LOCAL_URL;
            findViewById(R.id.hint_textView).setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.hint_textView)).setText(url);
        }
    }

    @Override
    public void onBackPressed() {
        showAlert(getString(R.string.alert_finish_title), getString(R.string.alert_finish_message),
                new HFDefaultDialog.OnDialogCallback() {
                    @Override
                    public void onNegative() {
                    }

                    @Override
                    public void onPositive() {
                        finish();
                    }
                });

    }

    @Override
    public void showAlertSimpleMessage(String message) {
        if (TextUtils.isEmpty(message)) mTextViewAlertSimple.setText("");
        else {
            mTextViewAlertSimple.setText(message);
            mPasswordEdit.postDelayed(new Runnable() {//자연스럽게 보이게 하기 위해 딜레이 추가
                @Override
                public void run() {
                    mPasswordEdit.clearData();
                }
            }, 300);
        }
    }

    @Override
    public void showAlertAccountMessage(String message) {
        if (TextUtils.isEmpty(message)) mTextViewAlertAccount.setText("");
        else {
            mTextViewAlertAccount.setText(message);
        }
    }

    @Override
    public void playLoginAnimation() {
        mTextViewRevision.setVisibility(View.VISIBLE);
        Animation alpha = new AlphaAnimation(0.0f, 1.0f);
        alpha.setDuration(500);
        mTextViewRevision.startAnimation(alpha);

        int margin = HFCommonUtil.getPixelFromDimension(this, R.dimen.intro_icon_margin_top);

        mImageViewIcon.animate()
                .translationY(margin)
                .setDuration(DURATION_ICON)
                .start();

        float startScale = 1.0f;
        float endScale = 0.53f;
        Animation animScale = new ScaleAnimation(
                startScale, endScale,
                startScale, endScale,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        animScale.setFillAfter(true);
        animScale.setDuration(DURATION_ICON);
        mImageViewIcon.startAnimation(animScale);
    }

    @Override
    public void showSimpleLogin() {
        mLayoutSimpleLogin.setVisibility(View.VISIBLE);
        findViewById(R.id.intro_linearLayout).setVisibility(View.GONE);

        int DURATION_LAYOUT = 800;
        Animation anim = new AlphaAnimation(0.0f, 1.0f);
        anim.setDuration(DURATION_LAYOUT);
        mLayoutSimpleLogin.startAnimation(anim);

        playLoginAnimation();

        ((TextView) findViewById(R.id.simpleDepartment_textView)).setText(HFInfoUtil.getDepartmentText(this));
    }

    @Override
    public void showAccountLogin() {
        mLayoutAccountLogin.setVisibility(View.VISIBLE);
        findViewById(R.id.intro_linearLayout).setVisibility(View.GONE);

        int DURATION_LAYOUT = 800;

        Animation anim = new AlphaAnimation(0.0f, 1.0f);
        anim.setDuration(DURATION_LAYOUT);
        mLayoutAccountLogin.startAnimation(anim);

        playLoginAnimation();

        mLayoutAccountLogin.postDelayed(new Runnable() {
            @Override
            public void run() {
                mLoginEditId.showSoftInput();
            }
        }, DURATION_LAYOUT);
    }

    /**************************************************
     * Support methods
     **************************************************/
    private void checkLoginButton() {
        boolean enable = false;
        if (mLoginEditPw.getLength() > 0 && mLoginEditId.isValidEmail()) enable = true;
        findViewById(R.id.login_textView).setEnabled(enable);
    }

    /**
     * 유효성 검사
     */
    private boolean checkLoginData() {
        if (mLoginEditId.isEmpty()) {
            showAlertAccountMessage(getString(R.string.login_alert_empty_id));
            mLoginEditId.setFocus();
            return false;
        } else {
            showAlertAccountMessage("");
        }

        if (mLoginEditPw.isEmpty()) {
            showAlertAccountMessage(getString(R.string.login_alert_empty_pw));
            mLoginEditPw.setFocus();
            return false;
        } else {
            showAlertAccountMessage("");
        }

        return true;
    }

    /**************************************************
     * View.OnClickListener
     **************************************************/
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.department_linearLayout:
                    mLoginEditId.hideSoftInput();
                    mLoginEditPw.hideSoftInput();
                    mDepartmentPickerView.show();
                    break;
                case R.id.admin_view:
                    testIndex += 1;
                    testHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            testIndex = 0;

                        }
                    }, 5000);
                    if (testIndex > 10 && testIndex < 20) {
                        showAdmin();
                    }
                    break;
                case R.id.login_textView:
                    if (checkLoginData()) {
                        String member_id = mLoginEditId.getText().trim();
                        mPresenter.doAccountLogin(member_id, mLoginEditPw.getText());
                    }
                    break;
                case R.id.signup_textView:
                    mPresenter.doSignUp();
                    break;
                case R.id.resetPassword_textView:
                    showToast(R.string.alert_comming_soon);
                    break;
            }
        }
    };

    /**************************************************
     * ADMIN
     **************************************************/
    Handler testHandler = new Handler();
    int testIndex = 0;

    private void showAdmin() {
        new AdminInputDialog(IntroActivity.this, AdminInputDialog.ADMIN_TYPE.PASSWORD, new AdminInputDialog.OnDialogCallback() {
            @Override
            public void onPositive(@NonNull String message) {
                if ("SUPER".equals(message)) {
                    Intent intent = new Intent(IntroActivity.this, TestModeActivity.class);
                    startActivity(intent);
                    finish();
                } else if ("ADMIN".equals(message)) {
                    Intent intent = new Intent(IntroActivity.this, AdminModeActivity.class);
                    startActivity(intent);
                    finish();
                } else if ("DESIGN".equals(message)) {
                    Intent intent = new Intent(IntroActivity.this, TestDesignActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onWrongPassword() {
                showToast("Wrong password");
            }
        }).show();
    }

    /**************************************************
     * HFLoginEditTextView.OnLoginEditTextListener
     **************************************************/
    HFLoginEditTextView.OnLoginEditTextListener onLoginEditTextListener = new HFLoginEditTextView.OnLoginEditTextListener() {
        @Override
        public void onFocusChange(@NonNull HFLoginEditTextView v, boolean b) {
            switch (v.getId()) {
                case R.id.id_alertEditText:
                    mFocusId = b;
                    if (b) {
                        mLoginEditId.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mLoginEditId.setSelection(0);
                            }
                        }, 100);
                    }
                    break;
                case R.id.pw_alertEditText:
                    mFocusPw = b;
                    break;
            }
            if (mFocusId || mFocusPw)
                mScrollView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mScrollView.smoothScrollTo(0, 1000);
                    }
                }, 500);
        }

        @Override
        public void onImeActionNext(@NonNull HFLoginEditTextView v) {
            switch (v.getId()) {
                case R.id.id_alertEditText:
                    mLoginEditPw.setFocus();
                    break;
                case R.id.pw_alertEditText:

                    break;
            }
        }

        @Override
        public void onValueChanged(@NonNull HFLoginEditTextView v) {
            showAlertAccountMessage("");
            checkLoginButton();
        }
    };

    /**************************************************
     * NumberKeypadView.OnNumberKeypadListener
     **************************************************/
    HFNumberKeypadView.OnNumberKeypadListener onNumberKeypadListener = new HFNumberKeypadView.OnNumberKeypadListener() {
        @Override
        public void onNumberClicked(int num) {
            mPasswordEdit.setNum(num);
        }

        @Override
        public void onDeleteClicked() {
            mPasswordEdit.delNum();
        }

        @Override
        public void easterEgg() {
            showAccountLogin();
        }
    };

    /**************************************************
     * PasswordEditTextView.OnInputPasswordListener
     **************************************************/
    HFPasswordEditTextView.OnInputPasswordListener onInputPasswordListener = new HFPasswordEditTextView.OnInputPasswordListener() {
        @Override
        public void onCompleteInput(String password) {
            mPresenter.doSimpleLogin(password);
        }

        @Override
        public void onErrorMessage(String message) {
            showToast(message);
        }

        @Override
        public void onTextChanged() {
            if (mPasswordEdit.getText().length() > 0)
                showAlertSimpleMessage("");
        }
    };
    /**************************************************
     * HFDepartmentPickerView.OnItemSelectedListener
     **************************************************/
    HFDepartmentPickerView.OnItemSelectedListener onItemSelectedListener = new HFDepartmentPickerView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(@NonNull String text) {
            mTextViewDepartment.setText(text);
        }
    };

    /**************************************************
     * GestureDetector.SimpleOnGestureListener
     **************************************************/
    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDown(MotionEvent event) {
            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            findViewById(R.id.department_linearLayout).setVisibility(View.VISIBLE);
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
            return false;
        }
    }
}
