package com.phlx.wool.ui.splash;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.phlx.wool.BR;
import com.phlx.wool.R;
import com.phlx.wool.data.VMFactory;
import com.phlx.wool.databinding.ActivitySplashBinding;
import com.phlx.wool.db.DbUtil;
import com.phlx.wool.db.interf.DbQueryCallBack;
import com.phlx.wool.entity.Label;
import com.phlx.wool.ui.base.BaseActivity;

import org.greenrobot.greendao.query.WhereCondition;

import java.util.List;

public class SplashActivity extends BaseActivity<ActivitySplashBinding, SplashVM> {

    @Override
    public int initContentView(Bundle bundle) {
        return R.layout.activity_splash;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public SplashVM initViewModel() {
        VMFactory factory = VMFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(SplashVM.class);
    }

    @Override
    public void initData() {
        super.initData();
        showDialog("正在下载标签数据，请稍后");
        String sql = "TIMESTAMP IN " + "(SELECT MAX(TIMESTAMP) FROM LABEL)";
        WhereCondition.StringCondition stringCondition =
                new WhereCondition.StringCondition(sql);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<Label>() {
            @Override
            public void onSuccess(List<Label> result) {
                long inputTime = 0;
                if (result != null && result.size() > 0) {
                    inputTime = result.get(0).getTimestamp();
                }
                viewModel.requestLabel(1, inputTime, 100000);
            }

            @Override
            public void onFailed() {

            }
        }).queryAsync(Label.class, stringCondition);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.errorEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                showTip(s);
            }
        });
    }

    private void showTip(String content) {
        new MaterialDialog.Builder(this).title("系统信息").content(content)
                .cancelable(false).canceledOnTouchOutside(false)
                .positiveText("退出").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    dialog.dismiss();
                    finish();
                }
            }
        }).show();
    }

    @Override
    public void onBackPressed() {

    }
}
