package com.rera.mss.model

import com.rera.mss.config.LONG_STRING_FIELD_LENGTH
import javax.persistence.*
import javax.validation.constraints.NotBlank
import javax.validation.constraints.Size

@Entity
@Table(name = "Inverter")
data class Inverter(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id: Long = 0,

        @NotBlank
        @Size(max = LONG_STRING_FIELD_LENGTH)
        var manufacturer: String,

        @NotBlank
        var efficiency: Float,

        @NotBlank
        @ManyToOne
        @JoinColumn(name = "user_id")
        var user: User
) {
    @OneToMany(mappedBy = "inverter", cascade = [CascadeType.ALL], orphanRemoval = false)
    var inverterMonitoredAreas: MutableSet<MonitoredArea> = mutableSetOf()

    @OneToMany(mappedBy = "inverter", cascade = [CascadeType.ALL], orphanRemoval = false, fetch = FetchType.LAZY)
    var inverterMeasurements: MutableSet<InverterMeasurement> = mutableSetOf()

    fun addMonitoredArea(monitoredArea: MonitoredArea) {
        val inverterMonitoredArea = MonitoredArea(
                id = monitoredArea.id,
                inverter = this,
                user = monitoredArea.user,
                instrument = monitoredArea.instrument,
                description = monitoredArea.description
        )
        inverterMonitoredArea.monitoredAreaPvPanelAreas = monitoredArea.monitoredAreaPvPanelAreas
        inverterMonitoredAreas.add(inverterMonitoredArea)
    }

    fun removeMonitoredArea(monitoredArea: MonitoredArea): MonitoredArea {
        inverterMonitoredAreas.remove(monitoredArea)
        return monitoredArea
    }

    fun addInverterMeasurement(m: InverterMeasurement) {
        val inverterMonitoredArea = InverterMeasurement(
                inverter = this,
                readingType = m.readingType,
                readingValue = m.readingValue,
                measuredAt = m.measuredAt
        )
    }

}