package com.zyzf.coffeepreorder.ui.coffee

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.StrictMode
import androidx.lifecycle.ViewModel
import androidx.paging.PagingData
import com.jcraft.jsch.Channel
import com.jcraft.jsch.ChannelSftp
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchException
import com.jcraft.jsch.Session
import com.jcraft.jsch.SftpException
import com.zyzf.coffeepreorder.database.model.Coffee
import com.zyzf.coffeepreorder.database.repository.CartRepository
import com.zyzf.coffeepreorder.database.repository.CoffeeRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.util.Properties

class CoffeeListViewModel(
    private val coffeeRepository: CoffeeRepository,
    private val cartRepository: CartRepository
) : ViewModel() {
    val coffeeListUiState: Flow<PagingData<Coffee>> = coffeeRepository.getAllCoffees()

    suspend fun addCoffeeToCart(coffeeUid: Int) {
        cartRepository.insertCoffee(coffeeUid, 1)
    }
    suspend fun createCoffee(coffee: Coffee, imageUri: Uri, context: Context) {
        val newCoffee: Long = coffeeRepository.insert(coffee)
        val inputStream = context.contentResolver.openInputStream(imageUri)
        val bitmap = BitmapFactory.decodeStream(inputStream)

        val f = File(context.cacheDir, "coffee_image_$newCoffee.png")
        withContext(Dispatchers.IO) {
            f.createNewFile()
            val bos = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos)
            val bitmapdata = bos.toByteArray()
            val fos = FileOutputStream(f)
            fos.write(bitmapdata)
            fos.flush()
            fos.close()
        }

        copyFileToSftp(f, "/mnt/nextcloud/data/Zyzf/files/Images")
    }
    suspend fun editCoffee(coffee: Coffee, imageUri: Any?, context: Context) {
        val editedCoffee: Int = coffeeRepository.update(coffee)
        if (imageUri !is Uri) return
        val inputStream = context.contentResolver.openInputStream(imageUri)
        val bitmap = BitmapFactory.decodeStream(inputStream)

        val f = File(context.cacheDir, "coffee_image_$editedCoffee.png")
        withContext(Dispatchers.IO) {
            f.createNewFile()
            val bos = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos)
            val bitmapdata = bos.toByteArray()
            val fos = FileOutputStream(f)
            fos.write(bitmapdata)
            fos.flush()
            fos.close()
        }
        copyFileToSftp(f, "/mnt/nextcloud/data/Zyzf/files/Images")
    }
    suspend fun deleteCoffee(coffee: Coffee) {
        coffeeRepository.delete(coffee)
    }
}

const val REMOTE_HOST = "109.197.199.134"
const val USERNAME = "zyzf"
const val PASSWORD = "250303Zyzf-d-grad"
const val REMOTE_PORT = 2223

fun copyFileToSftp(srcFile: File, ftpPath: String): Boolean {

    var jschSession: Session? = null

    try {
        val jsch = JSch()
        jsch.setKnownHosts("/home/zyzf/.ssh/known_hosts")
        jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT)
        jschSession.setPassword(PASSWORD)

        val config = Properties()
        config["StrictHostKeyChecking"] = "no"
        jschSession.setConfig(config)

        val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)
        jschSession.connect(10000)
        val sftp: Channel = jschSession.openChannel("sftp")

        sftp.connect(5000)
        val channelSftp: ChannelSftp = sftp as ChannelSftp

        channelSftp.put(srcFile.absolutePath, ftpPath)
        channelSftp.exit()

    } catch (e: JSchException) {
        e.printStackTrace()
        return false
    } catch (e: SftpException) {
        e.printStackTrace()
        return false
    } finally {
        jschSession?.disconnect()
    }
    return true
}