/*
 * Copyright 2016 Sociedad Religiosa Servidores de María
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package srsm.controller

import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.scene.control.Label
import javafx.scene.control.TableView
import javafx.scene.control.TextField
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import srsm.G
import srsm.Message
import srsm.controller.util.integerFormat
import srsm.controller.util.required
import srsm.model.Actividad
import srsm.model.Asistencia
import srsm.model.Servidor

@Suppress("unused", "UNUSED_PARAMETER")
class Asistencia {
    @FXML lateinit private var descripcion: Label
    @FXML lateinit private var cedula: TextField
    @FXML lateinit private var tablaAsis: TableView<Servidor>

    var actividad: Actividad? = null

    fun init() {
        descripcion.text = actividad?.descripcion ?: "Actividad"
        update()
    }

    private fun update() {
        tablaAsis.items.clear()
        tablaAsis.items.addAll(G.db.getAsistenciaByActividad(actividad!!))
    }

    private fun marcar() {
        try {
            required(Pair("Cédula", cedula))
            integerFormat(Pair("Cédula", cedula))
        } catch (e: Exception) {
            return
        }

        val servidor = G.db.getServidorByCedula(cedula.text)
        if (servidor == null) {
            Message.error("No existe servidor con esa cédula")
        } else {
            if (!G.db.existeAsistencia(actividad!!, servidor)) {
                val a = Asistencia()
                a.servidorID = servidor.id
                a.actividadID = actividad!!.id

                G.db.createAsistencia(a)
            } else {
                Message.error("Asistencia ya marcada")
            }
        }
        cedula.clear()
        cedula.requestFocus()
        update()
    }

    @FXML
    private fun initialize() {

    }

    @FXML
    private fun agregarOnAction(event: ActionEvent) {
        marcar()
    }

    @FXML
    private fun eliminarOnAction(event: ActionEvent) {
        tablaAsis.selectionModel.selectedItem?.let { s ->
            val asistencia = G.db.getAsistencia(actividad!!, s)

            if (asistencia != null) {
                G.db.deleteAsistencia(asistencia)
                update()
            }
        }
    }

    @FXML fun onKeyPressed(event: KeyEvent) {
        if (event.code == KeyCode.ENTER) {
            marcar()
        }
    }
}
