package com.yutou.jianr_mg.views;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Switch;

import com.yutou.jianr_mg.Databases.JianRDataDataBase;
import com.yutou.jianr_mg.R;
import com.yutou.jianr_mg.Tools.Utils;
import com.yutou.jianr_mg.services.WindowsService;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.materialdialog.MaterialDialog;

public class WindowsStartActivity extends AppCompatActivity implements View.OnClickListener {
    private Switch saveData;
    private Spinner dataType;
    private Button typeAdd;
    private Button typeRemove;
    private Spinner dataName;
    private Button nameAdd;
    private Button nameRemove;
    private LinearLayout dataConfig;
    private Button start;
    private Button help;
    private Button updata;
    ArrayAdapter typeAdapter;
    ArrayAdapter nameAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_windows_start);
        JianRDataDataBase.init();
        initView();
    }

    private void initView() {
        saveData = findViewById(R.id.saveData);
        dataType = findViewById(R.id.dataType);
        typeAdd = findViewById(R.id.typeAdd);
        typeRemove = findViewById(R.id.typeRemove);
        dataName = findViewById(R.id.dataName);
        nameAdd = findViewById(R.id.nameAdd);
        nameRemove = findViewById(R.id.nameRemove);
        dataConfig = findViewById(R.id.dataConfig);
        start = findViewById(R.id.start);
        help = findViewById(R.id.help);
        updata = findViewById(R.id.updata);

        typeAdd.setOnClickListener(this);
        typeRemove.setOnClickListener(this);
        nameAdd.setOnClickListener(this);
        nameRemove.setOnClickListener(this);
        start.setOnClickListener(this);
        help.setOnClickListener(this);
        updata.setOnClickListener(this);


        saveData.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                dataConfig.setVisibility(View.VISIBLE);
                saveData.setTag(true);
            } else {
                dataConfig.setVisibility(View.GONE);
                saveData.setTag(false);
            }
        });
        saveData.setTag(true);
       typeAdapter=new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item,getType());
        nameAdapter=new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item,getName(null));
        dataName.setAdapter(nameAdapter);
        dataType.setAdapter(typeAdapter);
        dataType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                reloadSpinner();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        reloadSpinner();
    }
    private void reloadSpinner(){
        nameAdapter.clear();
        typeAdapter.clear();
        typeAdapter.addAll(getType());
        try {
            nameAdapter.addAll(getName(dataType.getSelectedItem().toString()));
        }catch (Exception e){
            nameAdapter.addAll(getName(null));
        }

       nameAdapter.notifyDataSetChanged();
       typeAdapter.notifyDataSetChanged();
    }
    public List<String> getType() {
        List<String> list = new ArrayList<>();
        try {
           list.addAll(JianRDataDataBase.init().getTypes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list.size() == 0) {
            list.add("-请从右侧按钮添加-");
        }
        return list;
    }

    public List<String> getName(String type) {
        List<String> list = new ArrayList<>();
        try {
           list.addAll(JianRDataDataBase.init().getNames(type));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list.size() == 0) {
            list.add("-请从右侧按钮添加-");
        }
        return list;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.typeAdd:
                saveType();
                break;
            case R.id.typeRemove:
                removeType();
                break;
            case R.id.nameAdd:
                saveName();
                break;
            case R.id.nameRemove:
                removeName();
                break;
            case R.id.updata:
                Intent gameData=new Intent(this,GameDataActivity.class);
                startActivity(gameData);
                break;
            case R.id.start:
                Intent intent = new Intent(this, WindowsService.class);
                intent.putExtra("saveData", ((boolean) saveData.getTag()));
                if((boolean)saveData.getTag()) {
                    intent.putExtra("dataType", dataType.getSelectedItem().toString());
                    intent.putExtra("dataName", dataName.getSelectedItem().toString());
                }
                startService(intent);
                finish();
                break;
            case R.id.help:
                Intent hpIntent=new Intent(this,WebActivity.class);
                hpIntent.putExtra("url","http://bbs.jianrmod.cn/forum.php?mod=viewthread&tid=185&page=1&extra=#pid340");
                startActivity(hpIntent);
                break;
        }
    }

    public void removeType() {
        MaterialDialog dialog = new MaterialDialog(this);
        dialog.setTitle("删除分类");
        dialog.setMessage("确定删除 " + dataType.getSelectedItem().toString() + " 分类？" +
                "\n删除后，该分类下的数据库将无法访问");
        dialog.setNegativeButton("取消", view -> dialog.dismiss());
        dialog.setPositiveButton("确定", view -> {
            try {
                JianRDataDataBase.init().removeType(dataType.getSelectedItem().toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            reloadSpinner();
            dialog.dismiss();
        });
        dialog.show();
    }
    public void removeName() {
        MaterialDialog dialog = new MaterialDialog(this);
        dialog.setTitle("删除数据库");
        dialog.setMessage("确定删除 " + dataName.getSelectedItem().toString() + " 数据库？" +
                "\n删除后，该数据库将无法访问");
        dialog.setNegativeButton("取消", view -> dialog.dismiss());
        dialog.setPositiveButton("确定", view -> {
            try {
                if(dataType.getSelectedItem().toString().equals("-请从右侧按钮添加-")){
                    Utils.toast(this, "请先选择分类");
                    return;
                }
                JianRDataDataBase.init().removeName(dataName.getSelectedItem().toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            reloadSpinner();
            dialog.dismiss();
        });
        dialog.show();
    }

    public void saveType() {
        MaterialDialog dialog = new MaterialDialog(this);
        dialog.setTitle("添加分类");
        EditText editText = new EditText(this);
        editText.setHint("分类名称（如活动、日常、默认等自定义）");
        dialog.setContentView(editText);
        dialog.setNegativeButton("取消", view -> {
            dialog.dismiss();
        });
        dialog.setPositiveButton("保存", view -> {
            if (Utils.testStringIsNull(editText.getText().toString())) {
                Utils.toast(this, "请输入分类名称");
                editText.setText("默认");
                return;
            }
            try {
                JianRDataDataBase.init().addType(editText.getText().toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            reloadSpinner();
            dialog.dismiss();
        });
        dialog.show();
    }

    public void saveName() {
        MaterialDialog dialog = new MaterialDialog(this);
        dialog.setTitle("添加数据库");
        EditText editText = new EditText(this);
        editText.setHint("数据库名称（如活动、日常、默认等自定义）");
        dialog.setContentView(editText);
        dialog.setNegativeButton("取消", view -> {
            dialog.dismiss();
        });
        dialog.setPositiveButton("保存", view -> {
            if (Utils.testStringIsNull(editText.getText().toString())) {
                Utils.toast(this, "请输入数据库名称");
                editText.setText("默认");
                return;
            }
            if(dataType.getSelectedItem().toString().equals("-请从右侧按钮添加-")){
                Utils.toast(this, "请先选择分类");
                return;
            }
            try {
                JianRDataDataBase.init().addName(dataType.getSelectedItem().toString(),editText.getText().toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            reloadSpinner();
            dialog.dismiss();
        });
        dialog.show();
    }
}
