package io.openim.android.demo.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import io.openim.android.demo.databinding.ActivityEditTextBinding;
import io.openim.android.ouicore.base.BaseActivity;
import io.openim.android.ouicore.base.BaseViewModel;
import io.openim.android.ouicore.utils.Constants;
import io.openim.android.ouicore.utils.OnDedrepClickListener;

/**
 * 编辑修改
 */
public class EditTextActivity extends BaseActivity<BaseViewModel, ActivityEditTextBinding> {

    public static final String TITLE = "title";
    public static final String INIT_TXT = "init_txt";
    public static final String MAX_LENGTH = "max_length";
    public static final String TIPS = "tips";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindViewDataBinding(ActivityEditTextBinding.inflate(getLayoutInflater()));
        sink();
        initView();
    }

    private void initView() {
        String text = getIntent().getStringExtra(INIT_TXT);
        String tips = getIntent().getStringExtra(TIPS);
        view.tips.setText(tips == null ? getString(io.openim.android.ouicore.R.string.new_2) : tips);
        view.save.setEnabled(!TextUtils.isEmpty(text));
        view.title.setText(getIntent().getStringExtra(TITLE));
        view.edit.setText(text);
        int maxLength = getIntent().getIntExtra(MAX_LENGTH, -1);
        if (maxLength != -1) {
            view.edit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
        }
        view.edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                view.save.setEnabled(!TextUtils.isEmpty(editable.toString()));
            }
        });
        view.save.setOnClickListener(new OnDedrepClickListener() {
            @Override
            public void click(View v) {
                setResult(RESULT_OK, new Intent().putExtra(Constants.K_RESULT,
                        view.edit.getText().toString()));
                finish();
            }
        });
    }
}
