package com.app.duck.ui;

import static com.app.duck.Config.EVENT_UPDATE_CONFIG;
import static com.app.duck.Config.INTENT_EDIT_INI;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.MaterialDialog;
import com.app.duck.BaseActivity;
import com.app.duck.R;
import com.app.duck.database.AppDatabase;
import com.app.duck.database.Config;
import com.app.duck.databinding.ActivityIniEditBinding;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.UUID;

import io.reactivex.Completable;
import io.reactivex.CompletableObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class IniEditActivity extends BaseActivity<ActivityIniEditBinding> {


    private Config config;
    private String name = "";

    @Override
    public void initView() {
        initToolbar();
        LiveEventBus.get(INTENT_EDIT_INI, Config.class).observeSticky(this, value -> {
            config = value;
            b.editText.setText(config.getCfg(), 1);
            b.toolbar.setTitle(TextUtils.isEmpty(config.getName()) ? getString(R.string.noName) : config.getName());
        });

        if (getIntent() != null) {

            name = getIntent().getStringExtra("newKey");
        }
    }


    private void initToolbar() {
        setSupportActionBar(b.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        b.toolbar.setNavigationOnClickListener(v -> finish());
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_template:
                startActivity(new Intent(IniEditActivity.this, TemplateActivity.class));
                break;
            case R.id.action_save:
                actionSave();
                break;

        }
        return super.onOptionsItemSelected(item);
    }


    private void actionSave() {
        new MaterialDialog.Builder(this)
                .title(TextUtils.isEmpty(config.getName()) ? R.string.titleInputFileName : R.string.titleModifyFileName)
                .canceledOnTouchOutside(false)
                .autoDismiss(false)
                .negativeText(R.string.cancel)
                .positiveText(R.string.done)
                .onNegative((dialog, which) -> dialog.dismiss())
                .input("", TextUtils.isEmpty(config.getName()) ? name : config.getName(), false, (dialog, input) ->
                {
                    config.setName(input.toString())
                            .setCfg(b.editText.getText());
                    Completable action =
                            TextUtils.isEmpty(config.getUid()) ?
                                    AppDatabase.getInstance(IniEditActivity.this)
                                            .configDao()
                                            .insert(config.setUid(UUID.randomUUID().toString())) :
                                    AppDatabase.getInstance(IniEditActivity.this)
                                            .configDao()
                                            .update(config);
                    action
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new CompletableObserver() {
                                @Override
                                public void onSubscribe(@NonNull Disposable d) {

                                }

                                @Override
                                public void onComplete() {
                                    Toast.makeText(IniEditActivity.this.getApplicationContext(), R.string.tipSaveSuccess, Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                    LiveEventBus.get(EVENT_UPDATE_CONFIG).post(config);
                                    finish();
                                }

                                @Override
                                public void onError(@NonNull Throwable e) {
                                    Toast.makeText(IniEditActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();

                                }
                            });
                }).show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_add_text, menu);
        return true;
    }
}
