package com.example.kanalearner;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import java.util.List;

public class TestSettingsActivity extends OptionsActivity implements AdapterView.OnItemSelectedListener {
    Spinner typeSpinner;
    Spinner testSpinner;
    Spinner difficultySpinner;

    DbHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testsettings);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        typeSpinner = (Spinner) findViewById(R.id.spinner_type);
        testSpinner = (Spinner) findViewById(R.id.spinner_test);
        difficultySpinner = (Spinner) findViewById(R.id.spinner_difficulty);

        typeSpinner.setOnItemSelectedListener(this);
        testSpinner.setOnItemSelectedListener(this);
        difficultySpinner.setOnItemSelectedListener(this);

        dbHelper = new DbHelper(this);

        updateTypeList();
        updateTestList();
        updateDifficultyList();
    }

    public void startClicked(View view) {
        Intent i = new Intent(this, TestActivity.class);

        i.putExtra("typeId", ((DbHelper.Type)typeSpinner.getSelectedItem()).getId());
        i.putExtra("testId", ((DbHelper.Test)testSpinner.getSelectedItem()).getId());
        i.putExtra("difficultyId", ((DbHelper.Difficulty) difficultySpinner.getSelectedItem()).getId());

        startActivity(i);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (parent == typeSpinner) {
            updateTestList();
        }
    }

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

    private void updateTypeList() {
        ArrayAdapter<DbHelper.Type> adapter = new ArrayAdapter<DbHelper.Type>(this, android.R.layout.simple_spinner_item, dbHelper.getAllTypes());
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        typeSpinner.setAdapter(adapter);
    }

    private void updateTestList() {
        List<DbHelper.Test> items = dbHelper.getTestsForType(((DbHelper.Type) typeSpinner.getSelectedItem()).getId());
        ArrayAdapter<DbHelper.Test> adapter = new ArrayAdapter<DbHelper.Test>(this, android.R.layout.simple_spinner_item, items);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        testSpinner.setAdapter(adapter);
    }

    private void updateDifficultyList() {
        ArrayAdapter<DbHelper.Difficulty> adapter = new ArrayAdapter<DbHelper.Difficulty>(this, android.R.layout.simple_spinner_item, dbHelper.getAllDifficulties());
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        difficultySpinner.setAdapter(adapter);
    }
}