package llc.arma.ble.data.repository

import android.app.Application
import android.icu.text.SimpleDateFormat
import android.os.Environment
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import com.patrykandpatrick.vico.core.entry.ChartEntryModelProducer
import llc.arma.ble.R
import llc.arma.ble.app.ui.screen.inspection.host.view.HostEntry
import llc.arma.ble.app.ui.screen.inspection.host.view.colorsStack
import llc.arma.ble.domain.model.Ble
import llc.arma.ble.domain.repository.XlsxRepository
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.apache.poi.util.IOUtils
import org.apache.poi.xssf.usermodel.XSSFSheet
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.Date
import javax.inject.Inject


class XlsxRepositoryImpl @Inject constructor(
    private val application: Application
) : XlsxRepository {

    override fun exportAccelDataToXls(
        bleName: String,
        data: List<Ble.Accelerometer.HistoryPoint>
    ): File {

        val fileNameDateFormat = SimpleDateFormat("yyyy-MM-dd_HH-mm")
        val fileName = "${fileNameDateFormat.format(Date(System.currentTimeMillis()))}.xlsx"

        val formatter = SimpleDateFormat("dd.MM.yyyy HH:mm")

        File(application.filesDir.absolutePath).mkdirs()
        val mailFile = File(application.filesDir, fileName)

        mailFile.createNewFile()

        when(data.firstOrNull()){
            is Ble.Accelerometer.HistoryPoint.Vibration -> {
                IOUtils.copy(application.resources.openRawResource(R.raw.measure_single_axis), FileOutputStream(mailFile))
            }
            else -> {
                IOUtils.copy(application.resources.openRawResource(R.raw.measure_multiple_axis), FileOutputStream(mailFile))
            }
        }

        val fileIn = FileInputStream(mailFile)
        val workbook = WorkbookFactory.create(fileIn)
        val worksheet = workbook.getSheetAt(0) as XSSFSheet

        data.withIndex().forEach {

            val row = worksheet.createRow(it.index + 1)
            val dateX = row.createCell(0)
            val dateY = row.createCell(2)
            val dateZ = row.createCell(4)
            val x = row.createCell(1)
            val y = row.createCell(3)
            val z = row.createCell(5)

            when(val value = it.value){
                is Ble.Accelerometer.HistoryPoint.Angle -> {
                    dateX.setCellValue(formatter.format(Date(value.date)))
                    dateY.setCellValue(formatter.format(Date(value.date)))
                    dateZ.setCellValue(formatter.format(Date(value.date)))
                    x.setCellValue(value.x.toDouble())
                    y.setCellValue(value.y.toDouble())
                    z.setCellValue(value.z.toDouble())
                }
                is Ble.Accelerometer.HistoryPoint.Vibration -> {
                    dateX.setCellValue(formatter.format(Date(value.date)))
                    x.setCellValue(value.value.toDouble())
                }

                is Ble.Accelerometer.HistoryPoint.Acceleration -> {
                    dateX.setCellValue(formatter.format(Date(value.date)))
                    dateY.setCellValue(formatter.format(Date(value.date)))
                    dateZ.setCellValue(formatter.format(Date(value.date)))
                    x.setCellValue(value.x.toDouble())
                    y.setCellValue(value.y.toDouble())
                    z.setCellValue(value.z.toDouble())
                }

                is Ble.Accelerometer.HistoryPoint.Rotation -> {
                    dateX.setCellValue(formatter.format(Date(value.date)))
                    x.setCellValue(value.value.toDouble())
                }
            }
        }

        fileIn.close()
        val saveFos = FileOutputStream(mailFile)
        workbook.write(saveFos)
        saveFos.close()

        val sharedFile = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName)
        sharedFile.createNewFile()

        val sharedSaveFos = FileOutputStream(sharedFile)
        workbook.write(sharedSaveFos)
        sharedSaveFos.close()

        workbook.close()

        return mailFile
    }

    override fun exportHostDataToXls(bleName: String, data: List<Ble.Host.HistoryPoint>): File {
        val fileNameDateFormat = SimpleDateFormat("yyyy-MM-dd_HH-mm")
        val fileName = "${fileNameDateFormat.format(Date(System.currentTimeMillis()))}.xlsx"

        val formatter = SimpleDateFormat("dd.MM.yyyy HH:mm")

        File(application.filesDir.absolutePath).mkdirs()
        val mailFile = File(application.filesDir, fileName)

        mailFile.createNewFile()

        IOUtils.copy(application.resources.openRawResource(R.raw.host_history), FileOutputStream(mailFile))

        val fileIn = FileInputStream(mailFile)
        val workbook = WorkbookFactory.create(fileIn)
        val worksheet = workbook.getSheetAt(0) as XSSFSheet

        val row = worksheet.createRow(0)
        row.createCell(0).setCellValue("Date")

        data.forEachIndexed { index, historyPoint ->

            row.createCell(index).setCellValue(formatter.format(Date(historyPoint.date)))

        }

        data.flatMap { it.value }.distinct().forEachIndexed { rowIndex, serial ->

            val row = worksheet.createRow(rowIndex + 1)
            row.createCell(0).setCellValue(serial)

            data.forEachIndexed { index, historyPoint ->

                row.createCell(index + 1)
                    .setCellValue(
                        if(historyPoint.value.contains(serial)) 1.0 else 0.0
                    )
            }

        }

        fileIn.close()
        val saveFos = FileOutputStream(mailFile)
        workbook.write(saveFos)
        saveFos.close()

        println(fileName)

        val sharedFile = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName)
        sharedFile.createNewFile()

        val sharedSaveFos = FileOutputStream(sharedFile)
        workbook.write(sharedSaveFos)
        sharedSaveFos.close()

        workbook.close()

        return mailFile
    }

}