package kr.co.icontrols.iotplatform;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

import kr.co.icontrols.iotplatform.utils.SharedPrefUtil;

import static kr.co.icontrols.iotplatform.utils.CommonUtils.DismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getCircleBitmap;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getGroupImageResource;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.setupUI;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_01;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_02;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_03;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_04;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_05;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_06;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_07;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_08;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_09;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_00_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_01_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_02_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_03_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_04_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_05_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_06_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_07_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_08_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_09_STRING;

public class PopupActivity extends AppCompatActivity implements View.OnClickListener {
    /**
     * 일반적인 팝업
     */
    public final static int MODE_NORMAL = 1;
    /**
     * Yes, No 버튼이 포함된 팝업
     */
    public final static int MODE_YESNO = 2;
    /**
     * 버튼 없는 팝업
     */
    public final static int MODE_NO_BUTTON = 3;
    /**
     * 일반적인 팝업(아이콘 표시)
     */
    public final static int MODE_NORMAL_WITH_ICON = 4;
    /**
     * Yes, No 버튼이 포함된 팝업(아이콘 표시)
     */
    public final static int MODE_YESNO_WITH_ICON = 5;
    /**
     * Yes, No 버튼이 포함된 팝업(체크박스 표시)
     */
    public final static int MODE_YESNO_WITH_CHK = 6;
    /**
     * 자동 로그인 팝업
     */
    public final static int MODE_AUTO_LOGIN = 7;
    /**
     * 입력박스 팝업
     */
    public final static int MODE_INPUT = 8;
    /**
     * 그룹이미지 팝업
     */
    public final static int MODE_SELECT_GROUP_IMG = 9;

    /**
     * Bluetooth ON 팝업
     */
    public final static int MODE_ENABLE_BT = 10;

    /**
     * 재실모드 시간 설정 팝업
     */
    public final static int MODE_SET_JAESIL_TIME = 11;

    public final static String POPUP_MODE = "popup_mode";
    public final static String POPUP_TITLE_TEXT = "popup_title_text";
    public final static String POPUP_BODY_TEXT = "popup_body_text";
    public final static String POPUP_BODY_RED_MARK = "popup_body_mark";
    public final static String POPUP_OK_BUTTON_TEXT = "popup_ok_button_text";
    public final static String POPUP_CANCEL_BUTTON_TEXT = "popup_cancel_button_text";
    public final static String POPUP_TIMEOUT = "popup_timeout";
    public final static String POPUP_BUNDLE = "popup_bundle";
    public final static String POPUP_INPUT = "popup_input";
    public final static String POPUP_INPUT_MIN = "popup_input_min";
    public final static String POPUP_INPUT_MAX = "popup_input_max";
    public final static String POPUP_IMG_INDEX = "popup_img_index";
    public final static String POPUP_TIME_INDEX = "popup_time_index";

    public final static int DEFAULT_POPUP_TIMEOUT = (2 * 1000);


    private Timer mTimer;
    private Handler mHandler;

    private int mEntryMode;
    private Activity mActivity;
    private RelativeLayout mConfirmBtn;
    private RelativeLayout mCancelBtn;
    private TextView mTxt_popup_ok, mTxt_popup_cancel;
    private String mBodyText;
    private String mTitleText;
    private EditText mTxtInput;
    private int mTimeout;
    private Bundle mBundle;
    private int mSelectedImgIndex = 0;
    private int mSelectedTime = 0;
    private int inputMinLenght = 0;
    private int inputMaxLenght = 0;

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

        mEntryMode = 0;
        mActivity = this;

        Intent intent = getIntent();
        mEntryMode = intent.getIntExtra(POPUP_MODE, 0);
        mTimeout = intent.getIntExtra(POPUP_TIMEOUT, 0);
        mBundle = intent.getBundleExtra(POPUP_BUNDLE);

        if(mEntryMode == MODE_NORMAL || mEntryMode == MODE_YESNO || mEntryMode == MODE_NO_BUTTON || mEntryMode == MODE_NORMAL_WITH_ICON || mEntryMode == MODE_YESNO_WITH_ICON || mEntryMode == MODE_YESNO_WITH_CHK) {
            setContentView(R.layout.activity_popup);

            mTitleText = intent.getStringExtra(POPUP_TITLE_TEXT);
            TextView txtTitle = (TextView) findViewById(R.id.txtTitle);
            if(mTitleText == null || mTitleText.isEmpty()){
                txtTitle.setVisibility(View.GONE);
            } else {
                txtTitle.setVisibility(View.VISIBLE);
                txtTitle.setText(mTitleText);
            }
            mBodyText = intent.getStringExtra(POPUP_BODY_TEXT);
            TextView txtBody = (TextView) findViewById(R.id.txtBody);
            if(mBodyText == null || mBodyText.isEmpty()){
                txtBody.setVisibility(View.GONE);
            } else {
                txtBody.setVisibility(View.VISIBLE);
                txtBody.setText(mBodyText);
            }

            if(mEntryMode == MODE_NORMAL_WITH_ICON || mEntryMode == MODE_YESNO_WITH_ICON) {
                findViewById(R.id.imgWarning).setVisibility(View.VISIBLE);
                findViewById(R.id.chkDontShow).setVisibility(View.GONE);
            } else if(mEntryMode == MODE_YESNO_WITH_CHK) {
                findViewById(R.id.chkDontShow).setVisibility(View.VISIBLE);
                findViewById(R.id.imgWarning).setVisibility(View.GONE);
            } else {
                findViewById(R.id.imgWarning).setVisibility(View.GONE);
                findViewById(R.id.chkDontShow).setVisibility(View.GONE);
            }

            if(mTitleText == null || mTitleText.length() == 0) {
                txtTitle.setVisibility(View.GONE);
            } else {
                txtTitle.setVisibility(View.VISIBLE);
            }
        } else if(mEntryMode == MODE_AUTO_LOGIN) {
            setContentView(R.layout.activity_popup_auto_login);

            final LinearLayout layoutAutoLogin = findViewById(R.id.layoutAutoLogin);
            final ImageView imgAutoLogin = findViewById(R.id.imgAutoLogin);

            layoutAutoLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isAutoLogin = SharedPrefUtil.getBoolean(SharedPrefUtil.AUTO_LOGIN, SharedPrefUtil.DEFAULT_AUTO_LOGIN);
                    if(isAutoLogin) {
                        layoutAutoLogin.setBackgroundResource(R.drawable.button_white_line_gray);
                        imgAutoLogin.setImageResource(R.drawable.ui_chk);
                    } else {
                        layoutAutoLogin.setBackgroundResource(R.drawable.button_yellow);
                        imgAutoLogin.setImageResource(R.drawable.ui_chk_chked);
                    }
                    SharedPrefUtil.putBoolean(SharedPrefUtil.AUTO_LOGIN,!isAutoLogin);
                }
            });

            if(SharedPrefUtil.getBoolean(SharedPrefUtil.AUTO_LOGIN, SharedPrefUtil.DEFAULT_AUTO_LOGIN)) {
                layoutAutoLogin.setBackgroundResource(R.drawable.button_yellow);
                imgAutoLogin.setImageResource(R.drawable.ui_chk_chked);
            } else {
                layoutAutoLogin.setBackgroundResource(R.drawable.button_white_line_gray);
                imgAutoLogin.setImageResource(R.drawable.ui_chk);
            }
        } else if(MODE_INPUT == mEntryMode){
            setContentView(R.layout.activity_popup_input);
            //setupUI(this, findViewById(R.id.layoutMain));

            inputMinLenght = intent.getIntExtra(POPUP_INPUT_MIN, 0);
            inputMaxLenght = intent.getIntExtra(POPUP_INPUT_MAX,0);

            mTxtInput = findViewById(R.id.txtInput);

            mTitleText = intent.getStringExtra(POPUP_TITLE_TEXT);
            TextView txtTitle = (TextView) findViewById(R.id.txtTitle);
            if(mTitleText == null || mTitleText.isEmpty()){
                txtTitle.setVisibility(View.GONE);
            } else {
                txtTitle.setVisibility(View.VISIBLE);
                txtTitle.setText(mTitleText);
            }
            mBodyText = intent.getStringExtra(POPUP_BODY_TEXT);
            TextView txtBody = (TextView) findViewById(R.id.txtBody);
            if(mBodyText == null || mBodyText.isEmpty()){
                txtBody.setVisibility(View.GONE);
            } else {
                txtBody.setVisibility(View.VISIBLE);
                txtBody.setText(mBodyText);
            }

            if(mBundle!=null) {
                String strInput = mBundle.getString(POPUP_INPUT);
                mTxtInput.setText(strInput);
            } else {
                mTxtInput.setText("");
            }
        } else if(MODE_SELECT_GROUP_IMG == mEntryMode) {
            setContentView(R.layout.activity_popup_select_group_img);

            ((ImageView)findViewById(R.id.img01)).setImageBitmap(getCircleBitmap(getGroupImageResource(GROUP_IMG_01_STRING)));
            ((ImageView)findViewById(R.id.img02)).setImageBitmap(getCircleBitmap(getGroupImageResource(GROUP_IMG_02_STRING)));
            ((ImageView)findViewById(R.id.img03)).setImageBitmap(getCircleBitmap(getGroupImageResource(GROUP_IMG_03_STRING)));
            ((ImageView)findViewById(R.id.img04)).setImageBitmap(getCircleBitmap(getGroupImageResource(GROUP_IMG_04_STRING)));
            ((ImageView)findViewById(R.id.img05)).setImageBitmap(getCircleBitmap(getGroupImageResource(GROUP_IMG_05_STRING)));
            ((ImageView)findViewById(R.id.img06)).setImageBitmap(getCircleBitmap(getGroupImageResource(GROUP_IMG_06_STRING)));
            ((ImageView)findViewById(R.id.img07)).setImageBitmap(getCircleBitmap(getGroupImageResource(GROUP_IMG_07_STRING)));
            ((ImageView)findViewById(R.id.img08)).setImageBitmap(getCircleBitmap(getGroupImageResource(GROUP_IMG_08_STRING)));
            ((ImageView)findViewById(R.id.img09)).setImageBitmap(getCircleBitmap(getGroupImageResource(GROUP_IMG_09_STRING)));


            mTitleText = intent.getStringExtra(POPUP_TITLE_TEXT);
            TextView txtTitle = (TextView) findViewById(R.id.txtTitle);
            if(mTitleText == null || mTitleText.isEmpty()){
                txtTitle.setVisibility(View.GONE);
            } else {
                txtTitle.setVisibility(View.VISIBLE);
                txtTitle.setText(mTitleText);
            }
            mBodyText = intent.getStringExtra(POPUP_BODY_TEXT);
            TextView txtBody = (TextView) findViewById(R.id.txtBody);
            if(mBodyText == null || mBodyText.isEmpty()){
                txtBody.setVisibility(View.GONE);
            } else {
                txtBody.setVisibility(View.VISIBLE);
                txtBody.setText(mBodyText);
            }

            mSelectedImgIndex = intent.getIntExtra(POPUP_IMG_INDEX,1);
            changeSelectedImg(mSelectedImgIndex);
        } else if(mEntryMode == MODE_ENABLE_BT) {
            setContentView(R.layout.activity_popup);

            mTitleText = getString(R.string.bt_on_for_use_str);
            TextView txtTitle = (TextView) findViewById(R.id.txtTitle);
            txtTitle.setVisibility(View.VISIBLE);
            txtTitle.setText(mTitleText);

            TextView txtBody = (TextView) findViewById(R.id.txtBody);
            txtBody.setVisibility(View.GONE);

            if(mEntryMode == MODE_NORMAL_WITH_ICON || mEntryMode == MODE_YESNO_WITH_ICON) {
                findViewById(R.id.imgWarning).setVisibility(View.VISIBLE);
                findViewById(R.id.chkDontShow).setVisibility(View.GONE);
            } else if(mEntryMode == MODE_YESNO_WITH_CHK) {
                findViewById(R.id.chkDontShow).setVisibility(View.VISIBLE);
                findViewById(R.id.imgWarning).setVisibility(View.GONE);
            } else {
                findViewById(R.id.imgWarning).setVisibility(View.GONE);
                findViewById(R.id.chkDontShow).setVisibility(View.GONE);
            }
        } else if(mEntryMode == MODE_SET_JAESIL_TIME) {
            setContentView(R.layout.activity_popup_set_jaesil_time);
            mSelectedTime = intent.getIntExtra(POPUP_TIME_INDEX,60);
            changeSelectTime(mSelectedTime);
        }

        if (mTimeout > 0) {
            mHandler = new Handler();
            startDelayTimer(mTimeout);
        }

        mConfirmBtn = findViewById(R.id.popup_ok);
        mCancelBtn =  findViewById(R.id.popup_cancel);
        mTxt_popup_ok = findViewById(R.id.txt_popup_ok);
        mTxt_popup_cancel = findViewById(R.id.txt_popup_cancel);

        if (mEntryMode == MODE_NORMAL || mEntryMode == MODE_NORMAL_WITH_ICON) {
            mCancelBtn.setVisibility(View.GONE);
            findViewById(R.id.layout_round_ok).setVisibility(View.GONE);
            findViewById(R.id.button_line).setVisibility(View.GONE);
        } else if(mEntryMode == MODE_NO_BUTTON) {
            findViewById(R.id.popup_button_layout).setVisibility(View.GONE);
        } else if (mEntryMode == MODE_ENABLE_BT) {
            mCancelBtn.setVisibility(View.GONE);
            findViewById(R.id.layout_round_ok).setVisibility(View.GONE);
            findViewById(R.id.button_line).setVisibility(View.GONE);
            mTxt_popup_ok.setText(getString(R.string.bt_on_for_use_confirm_str));
        }

        if (intent.getStringExtra(POPUP_OK_BUTTON_TEXT) != null) {
            mTxt_popup_ok.setText(intent.getStringExtra(POPUP_OK_BUTTON_TEXT));
        }
        if (intent.getStringExtra(POPUP_CANCEL_BUTTON_TEXT) != null) {
            mTxt_popup_cancel.setText(intent.getStringExtra(POPUP_CANCEL_BUTTON_TEXT));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }
    }

    /**
     * 버튼 클릭에 대해 처리루틴 함수
     * @param view
     */
    @Override
    public void onClick(View view) {
        final View fv = view;
        fv.setEnabled(false);
        Timer buttonTimer = new Timer();
        buttonTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            fv.setEnabled(true);
                        } catch (Exception e){
                            e.printStackTrace();
                        } finally {

                        }
                    }
                });
            }
        }, 500);

        switch (view.getId()) {
            case R.id.popup_ok:
                if(mEntryMode == MODE_INPUT){
                    if(mTxtInput.getText().toString().length() == 0 || mTxtInput.getText().toString().isEmpty()) {
                        showNotiMsg(PopupActivity.this,"입력란이 비어있습니다.");
                        return;
                    } else if(inputMinLenght != 0 && mTxtInput.getText().toString().length() < inputMinLenght) {
                        showNotiMsg(PopupActivity.this,"최소 "+inputMinLenght+"자 이상을 입력해야합니다.");
                        return;
                    } else if(inputMaxLenght != 0 && mTxtInput.getText().toString().length() > inputMaxLenght) {
                        showNotiMsg(PopupActivity.this,"최대 "+inputMaxLenght+"자 이하를 입력해야합니다.");
                        return;
                    }

                    if(mBundle!=null) {
                        mBundle.putString(POPUP_INPUT,mTxtInput.getText().toString());
                    }
                } else if(mEntryMode == MODE_SELECT_GROUP_IMG) {
                    getIntent().putExtra(POPUP_IMG_INDEX,mSelectedImgIndex);
                } else if(mEntryMode == MODE_SET_JAESIL_TIME) {
                    getIntent().putExtra(POPUP_TIME_INDEX,mSelectedTime);
                }
                setResultAndFinish();
                break;

            case R.id.popup_cancel:
                setResult(RESULT_CANCELED, null);
                finish();
                break;

            case R.id.img01:
                changeSelectedImg(GROUP_01);
                break;
            case R.id.img02:
                changeSelectedImg(GROUP_02);
                break;
            case R.id.img03:
                changeSelectedImg(GROUP_03);
                break;
            case R.id.img04:
                changeSelectedImg(GROUP_04);
                break;
            case R.id.img05:
                changeSelectedImg(GROUP_05);
                break;
            case R.id.img06:
                changeSelectedImg(GROUP_06);
                break;
            case R.id.img07:
                changeSelectedImg(GROUP_07);
                break;
            case R.id.img08:
                changeSelectedImg(GROUP_08);
                break;
            case R.id.img09:
                changeSelectedImg(GROUP_09);
                break;
            case R.id.txtTime1:
                changeSelectTime(120);
                break;
            case R.id.txtTime2:
                changeSelectTime(90);
                break;
            case R.id.txtTime3:
                changeSelectTime(60);
                break;
            case R.id.txtTime4:
                changeSelectTime(50);
                break;
            case R.id.txtTime5:
                changeSelectTime(40);
                break;
            case R.id.txtTime6:
                changeSelectTime(30);
                break;
            case R.id.txtTime7:
                changeSelectTime(20);
                break;
            case R.id.txtTime8:
                changeSelectTime(10);
                break;
            case R.id.txtTime9:
                changeSelectTime(5);
                break;
        }
    }

    private void setResultAndFinish() {
        Intent intent = getIntent();
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 일정 시간 후에 팝업 사라게하는 함수
     * @param period
     */
    private void startDelayTimer(int period){
        if(mTimer != null){
            mTimer.cancel();
        }
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        DismissConnectDialog();
                        Intent intent = getIntent();
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
            }
        }, period);
    }

    /**
     * 이미지 팝업에서 이미지 선택시 UI 변경
     * @param index
     */
    private void changeSelectedImg(int index) {
        mSelectedImgIndex = index;
        ImageView[] imgList = new ImageView[]{
                null,
                findViewById(R.id.img01),
                findViewById(R.id.img02),
                findViewById(R.id.img03),
                findViewById(R.id.img04),
                findViewById(R.id.img05),
                findViewById(R.id.img06),
                findViewById(R.id.img07),
                findViewById(R.id.img08),
                findViewById(R.id.img09),
        };

        String groupImgString[] = {GROUP_IMG_00_STRING,
                GROUP_IMG_01_STRING,GROUP_IMG_02_STRING,GROUP_IMG_03_STRING,
                GROUP_IMG_04_STRING,GROUP_IMG_05_STRING,GROUP_IMG_06_STRING,
                GROUP_IMG_07_STRING,GROUP_IMG_08_STRING,GROUP_IMG_09_STRING,
        };

        for(int i = 1 ; i < imgList.length ; i++) {
            imgList[i].setImageBitmap(getCircleBitmap(getGroupImageResource(groupImgString[i]),mSelectedImgIndex==i));
        }
    }

    private void changeSelectTime(int time) {
        mSelectedTime = time;
        TextView textView[] = new TextView[]{
                findViewById(R.id.txtTime1),
                findViewById(R.id.txtTime2),
                findViewById(R.id.txtTime3),
                findViewById(R.id.txtTime4),
                findViewById(R.id.txtTime5),
                findViewById(R.id.txtTime6),
                findViewById(R.id.txtTime7),
                findViewById(R.id.txtTime8),
                findViewById(R.id.txtTime9),
        };

        int index = -1;
        switch (mSelectedTime) {
            case 120:
                index = 0;
                break;
            case 90:
                index = 1;
                break;
            case 60:
                index = 2;
                break;
            case 50:
                index = 3;
                break;
            case 40:
                index = 4;
                break;
            case 30:
                index = 5;
                break;
            case 20:
                index = 6;
                break;
            case 10:
                index = 7;
                break;
            case 5:
                index = 8;
                break;
            default:
                mSelectedTime = 60;
                index = 2;
                break;
        }

        for(int i = 0 ; i < textView.length ; i++) {
            if(index == i) {
                textView[i].setSelected(true);
            } else {
                textView[i].setSelected(false);
            }
        }
    }
}