package com.ads.cal.notes;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.ads.cal.notes.bean.DataBean;
import com.ads.cal.notes.dialog_fragment.DeleteFragment;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class NoteEditActivity extends BaseActivity {

    private DataBean dataBean;
    private boolean isCreateNote;
    private String oldContent;

    @Override
    int getContentLayoutId() {
        return R.layout.activity_edit;
    }

    private EditText editText;

    @Override
    void initView() {
        ImageView back = findViewById(R.id.back);
        ImageView delete = findViewById(R.id.delete);
        ImageView save = findViewById(R.id.save);
        editText = findViewById(R.id.ed_text);
        editText.requestFocus();
        editText.requestLayout();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                functionNote();
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DeleteFragment dialogFragment = new DeleteFragment();
                dialogFragment.show(getSupportFragmentManager(), "DeleteFragment");
            }
        });
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                functionNote();
            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count <= 0) {
                    if (delete.getVisibility() != View.GONE) {
                        delete.setVisibility(View.GONE);
                    }
                    if (save.getVisibility() != View.GONE) {
                        save.setVisibility(View.GONE);
                    }
                } else {
                    if (delete.getVisibility() != View.VISIBLE) {
                        delete.setVisibility(View.VISIBLE);
                    }
                    if (save.getVisibility() != View.VISIBLE) {
                        save.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    void intData() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        dataBean = (DataBean) intent.getSerializableExtra("data");
        if (dataBean == null || dataBean.content == null) {
            isCreateNote = true;
            return;
        }
        oldContent = dataBean.content;
        editText.setText(oldContent);
        editText.setSelection(oldContent.length());
    }

    private boolean startSave = false;
    private void functionNote() {
        if (startSave) {
            return;
        }
        startSave = true;
        String content = editText.getText().toString();
        if (oldContent != null && oldContent.equals(content)) {
            finish();
            return;
        }
        if (isCreateNote) {
            save(content);
        } else {
            update(content);
        }
    }

    private void save(String content) {
        if (TextUtils.isEmpty(content)) {
            delete();
            return;
        }
        long time = System.currentTimeMillis();
        Observable.fromCallable(() -> {
                    // 执行耗时操作
                    return BaseApplication.getDataBaseManager().insertData(content, time);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        LLog.d("onSubscribe   = ");
                    }

                    @Override
                    public void onNext(Long aLong) {
                        LLog.d("onNext   = "+aLong);
                        if (null == dataBean) {
                            dataBean = new DataBean();
                        }
                        LoadingActivity.instance(NoteEditActivity.this);
                        dataBean.content = content;
                        dataBean.time = time;
                        EventBus.getDefault().post(new EventBusMessage(Utils.EVENT_TYPE_SAVE, dataBean));
//                        Toast.makeText(NoteEditActivity.this, getResources().getString(R.string.save), Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LLog.d("onError   = "+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        LLog.d("onComplete");

                    }
                });
    }

    public void delete() {
        if (null == dataBean) {
            finish();
            return;
        }
        long time = dataBean.time;
        Utils.startTask(() -> {
            BaseApplication.getDataBaseManager().deleteData(time);
            runOnUiThread(() -> {
                EventBus.getDefault().post(new EventBusMessage(Utils.EVENT_TYPE_DELETE, dataBean));
                Toast.makeText(NoteEditActivity.this, getResources().getString(R.string.delete), Toast.LENGTH_SHORT).show();
                finish();
            });
        });
    }

    private void update(String content) {
        if (null == dataBean) {
            finish();
            return;
        }
        if (TextUtils.isEmpty(content)) {
            delete();
            return;
        }
        long updateTime = System.currentTimeMillis();
        Observable.fromCallable(() -> {
                    // 执行耗时操作
                    return BaseApplication.getDataBaseManager().updateData(content, dataBean.time, updateTime);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        LLog.d("onNext   = "+integer);
                        if (null == dataBean) {
                            dataBean = new DataBean();
                        }
                        LoadingActivity.instance(NoteEditActivity.this);
                        dataBean.content = content;
                        dataBean.updateTime = updateTime;
                        EventBus.getDefault().post(new EventBusMessage(Utils.EVENT_TYPE_SAVE, dataBean));
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    public void onBackPressed() {
        functionNote();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public static void invoke(Context context, DataBean dataBean) {
        Intent intent = new Intent(context, NoteEditActivity.class);
        intent.putExtra("data", dataBean);
        context.startActivity(intent);
    }
}
