package org.foxarmy.barcodescannerforemployees.activities

import android.app.Activity
import android.content.ContentValues
import android.os.Bundle
import android.provider.BaseColumns
import android.widget.Button
import android.widget.EditText
import org.foxarmy.barcodescannerforemployees.CategoriesContract
import org.foxarmy.barcodescannerforemployees.dataclasses.Category
import org.foxarmy.barcodescannerforemployees.DBStorageController
import org.foxarmy.barcodescannerforemployees.R

class AddCategoryActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_add_category)

        val extras = intent.extras
        val category = extras!!.get("category") as Category?

        val categoryNameTextEdit: EditText = findViewById(R.id.newCategoryName)

        categoryNameTextEdit.setText(category!!.name)

        findViewById<Button>(R.id.saveButton).setOnClickListener {
            val db = DBStorageController(this).writableDatabase

            if (category.id == 0) { // Inserting new category
                val values = ContentValues().apply {
                    put(CategoriesContract.CategoryEntry.CATEGORY_NAME, categoryNameTextEdit.text.toString())
                }

                db.insert(CategoriesContract.CategoryEntry.TABLE_NAME, null, values)
            } else { // Updating existing category
                val values = ContentValues().apply {
                    put(CategoriesContract.CategoryEntry.CATEGORY_NAME, categoryNameTextEdit.text.toString())
                }
                db.update(CategoriesContract.CategoryEntry.TABLE_NAME, values, "${BaseColumns._ID} = ?", arrayOf(category.id.toString()))
            }

            finish()
        }
    }
}