package com.lemonhc.mplus.model

import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import com.google.gson.Gson

data class Photo(var user: User, val context: Context) {
    lateinit var file: String
    lateinit var date: String
    lateinit var key: String
    var isSended: Boolean = false
    var helper: PhotoHelper = initHelper()

    companion object {
        fun list(user:User, context: Context):List<Pair<String, MutableList<Photo>>> {
            var returnMap: MutableList<Pair<String, MutableList<Photo>>> = mutableListOf()
            if (user.patientId.isEmpty()) {
                return returnMap
            }

            val helper = PhotoHelper(context, "Photo", null, 1)
            val db: SQLiteDatabase = helper.readableDatabase
            val cursor: Cursor = db.rawQuery(
                    "SELECT user, fileName, fileKey FROM Photo where userId='${user.patientId}' ORDER BY fileDate ASC", null
            )

            var photos = ArrayList<Photo>()
            while (cursor.moveToNext()) {
                val userData: User = Gson().fromJson(cursor.getString(0), User::class.java)
                var photo = Photo(userData, context)

                photo.file = cursor.getString(1)
                photo.key = cursor.getString(2)

                if (photo.recovery()) {
                    if (filter(user, photo)) {
                        photos.add(photo)
                    }
                }
            }

            val keySet: Set<String> = photos.map { it.key }.toSet()
            val keyList: List<String> = keySet.sorted().asReversed()

            for (key: String in keyList) {
                returnMap.add(Pair(key, photos.filter { it.key == key }.toMutableList()))
            }
            return returnMap
        }

        fun allList(user: User, context: Context): List<Pair<String, MutableList<Photo>>> {
            var returnMap: MutableList<Pair<String, MutableList<Photo>>> = mutableListOf()
            val helper = PhotoHelper(context, "Photo", null, 1)
            val db: SQLiteDatabase = helper.readableDatabase

            val cursor: Cursor = db.rawQuery("SELECT user, fileName, fileKey FROM Photo ORDER BY fileDate ASC", null)
            var photos = ArrayList<Photo>()
            while (cursor.moveToNext()) {
                val userData: User = Gson().fromJson(cursor.getString(0), User::class.java)
                var photo = Photo(userData, context)

                photo.file = cursor.getString(1)
                photo.key = cursor.getString(2)
                if (photo.recovery()) {
                    if (filter(user, photo)) {
                        photos.add(photo)
                    }
                }
            }

            val keySet: Set<String> = photos.map { it.key }.toSet()
            val keyList: List<String> = keySet.sorted().asReversed()

            for (key: String in keyList) {
                returnMap.add(Pair(key, photos.filter { it.key == key }.toMutableList()))
            }
            return returnMap
        }

        private fun filter(user: User, photo: Photo) = user.userId == photo.user.userId
    }
}

fun Photo.initHelper(): PhotoHelper {
    return PhotoHelper(context, "Photo", null, 1)
}

fun Photo.isSave(): Boolean {
    if (user.patientId.isEmpty() || key.isEmpty() || file.isEmpty()) {
        return false
    }

    val db: SQLiteDatabase = helper.readableDatabase
    val cursor: Cursor = db.rawQuery(
            "SELECT ID FROM Photo where userId='${user.patientId}' and fileKey='$key' and fileName='$file'", null
    )
    // moveToNext 다음에 데이터가 있으면 true 없으면 false
    return cursor.moveToNext()
}

fun Photo.save() {
    if (this.isSave()) {
        this.update()
        return
    }

    if (user.patientId.isEmpty() || user.patientNm.isEmpty() || user.age.isEmpty()
            || user.gender.isEmpty() || file.isEmpty() || key.isEmpty() || date.isEmpty()) {
        return
    }

    val db: SQLiteDatabase = helper.writableDatabase
    db.execSQL(
            """
               INSERT INTO Photo (userId, userName, userAge, userGender, fileName, fileDate, fileKey, fileSend, user) VALUES
               ('${user.patientId}', '${user.patientNm}', '${user.age}', '${user.gender}', '$file', '$date', '$key', '${if(isSended) 1 else 0}', '${Gson().toJson(user)}')
            """.trimIndent()
    )
}

fun Photo.update() {
    if (user.patientId.isEmpty() || user.patientNm.isEmpty() || user.age.isEmpty()
            || user.gender.isEmpty() || file.isEmpty() || key.isEmpty() || date.isEmpty()) {
        return
    }

    val db: SQLiteDatabase = helper.writableDatabase
    db.execSQL(
            """
                UPDATE Photo SET userName='${user.patientNm}', userAge='${user.age}', userGender='${user.gender}', fileDate='$date',
                fileSend='${if(isSended) 1 else 0}' where userId='${user.patientId}' and fileKey='$key' and fileName='$file'
            """.trimIndent()
    )
}

fun Photo.recovery(): Boolean {
    if (user.patientId.isEmpty() || file.isEmpty() || key.isEmpty()) {
        return false
    }

    val db: SQLiteDatabase = helper.readableDatabase
    val cursor: Cursor = db.rawQuery(
            "SELECT userName, userAge, userGender, fileDate, fileSend FROM Photo where userId='${user.patientId}' and fileKey='$key' and fileName='$file'", null
    )

    // next 메서드는 일치하는 레코드가 적어도 하나 이상인지 확인하기 위함
    if (cursor.moveToNext()) {
        user.patientNm = cursor.getString(0)
        user.age = cursor.getString(1)
        user.gender = cursor.getString(2)
        date = cursor.getString(3)
        isSended = (cursor.getInt(4) == 1)
        return true
    }
    return false
}

fun Photo.delete(): Boolean {
    if (user.patientId.isEmpty() || file.isEmpty() || key.isEmpty()) {
        return false
    }

    val db: SQLiteDatabase = helper.writableDatabase
    db.execSQL(
            "DELETE FROM Photo where userId='${user.patientId}' and fileKey='$key' and fileName='$file'"
    )
    return true
}
