package com.safecheckin.app.data.repository

import android.content.Context
import com.safecheckin.app.data.local.LocalDataSource
import com.safecheckin.app.data.model.CheckInRecord
import com.safecheckin.app.data.model.Contact
import kotlinx.coroutines.flow.Flow
import java.util.Calendar

class Repository(context: Context) {
    
    private val localDataSource = LocalDataSource(context)

    // Check-in operations
    val allCheckIns: Flow<List<CheckInRecord>> = localDataSource.checkIns

    suspend fun insertCheckIn(checkIn: CheckInRecord) {
        localDataSource.addCheckIn(checkIn)
    }

    suspend fun getCheckInForToday(): CheckInRecord? {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        val startOfDay = calendar.timeInMillis
        calendar.add(Calendar.DAY_OF_MONTH, 1)
        val endOfDay = calendar.timeInMillis
        
        // Get from flow - this is a simplified version
        return null // Will be handled in ViewModel
    }

    // Contact operations
    val allContacts: Flow<List<Contact>> = localDataSource.contacts

    suspend fun insertContact(contact: Contact) {
        localDataSource.addContact(contact)
    }

    suspend fun updateContact(contact: Contact) {
        localDataSource.updateContact(contact)
    }

    suspend fun deleteContact(contact: Contact) {
        localDataSource.deleteContact(contact)
    }

    // Settings
    val presetMessage: Flow<String> = localDataSource.presetMessage
    val gracePeriodHours: Flow<Int> = localDataSource.gracePeriodHours
    val gracePeriodMinutes: Flow<Int> = localDataSource.gracePeriodMinutes
    
    suspend fun setPresetMessage(message: String) {
        localDataSource.setPresetMessage(message)
    }
    
    suspend fun setGracePeriod(hours: Int, minutes: Int) {
        localDataSource.setGracePeriod(hours, minutes)
    }

    // SMTP Settings
    val smtpHost: Flow<String> = localDataSource.smtpHost
    val smtpPort: Flow<Int> = localDataSource.smtpPort
    val smtpUsername: Flow<String> = localDataSource.smtpUsername
    val smtpPassword: Flow<String> = localDataSource.smtpPassword
    val smtpSecurity: Flow<String> = localDataSource.smtpSecurity

    suspend fun setSmtpConfig(host: String, port: Int, username: String, password: String, security: String) {
        localDataSource.setSmtpConfig(host, port, username, password, security)
    }
}