package cz.muni.sutralog

import android.Manifest
import android.R.attr.path
import android.R.string
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.storage.StorageManager
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.documentfile.provider.DocumentFile
import com.google.android.material.card.MaterialCardView
import cz.muni.sutralog.data.CategoryPresentableListItem
import cz.muni.sutralog.data.RockPresentableListItem
import cz.muni.sutralog.databinding.ActivityMainBinding
import cz.muni.sutralog.repository.CategoryRepository
import cz.muni.sutralog.repository.RockRepository
import java.io.File
import java.time.LocalDate
import javax.xml.parsers.DocumentBuilder
import kotlin.random.Random


class MainActivity : AppCompatActivity() {
    // TODO for testing only. remove
    private val categoryRepository: CategoryRepository by lazy {
        CategoryRepository(applicationContext)
    }
    // TODO for testing only. remove
    private val rockRepository: RockRepository by lazy {
        RockRepository(applicationContext)
    }

    private val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    companion object {
        private const val CAMERA_PERMISSION_CODE = 100
        private const val STORAGE_PERMISSION_CODE = 101
    }

    private var sutralogPath = ""
    private lateinit var btnShowFolder: MaterialCardView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // TODO for testing only. remove

        sutralogPath = this.getExternalFilesDir(null).toString() + "/Sutralog/"
      //  sutralogPath = Environment.DIRECTORY_DOWNLOADS + "/Sutralog/"
        mockDatabase()

        requestPermissions(STORAGE_PERMISSION_CODE)
        requestPermissions(CAMERA_PERMISSION_CODE)
        rockRepository.saveRocks(setRockFolderPath(rockRepository.getAllRocks(), sutralogPath))

        setContentView(binding.root)
    }

    fun requestPermissions(requestCode: Int) {
        if (requestCode == STORAGE_PERMISSION_CODE) {
            var createFolders = false
            if (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                // Requesting the permission
                ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), STORAGE_PERMISSION_CODE)
            } else {
                createFolders = true
            }
            if (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                // Requesting the permission
                ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), STORAGE_PERMISSION_CODE)
            } else {
                createFolders = true
            }
            if (createFolders) {
                createRockFolders(rockRepository.getAllRocks())
            }
        }
        if (requestCode == CAMERA_PERMISSION_CODE) {
            if (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
                ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_CODE)
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int,
                                            permissions: Array<String>,
                                            grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == STORAGE_PERMISSION_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                createRockFolders(rockRepository.getAllRocks())

                Toast.makeText(this@MainActivity, "Storage Permission Granted", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this@MainActivity, "Storage Permission Denied", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun setRockFolderPath(rocks: List<RockPresentableListItem>, sutralogPath: String): List<RockPresentableListItem> {
        rocks.forEach {
            val path =  sutralogPath + it.id + "_" + it.name
            it.folderPath = path
        }
        return rocks
    }

    private fun mockDatabase() {
        categoryRepository.saveCategories(getMockedCategories())

        val rocks = getMockedRocks()
        rockRepository.saveRocks(getMockedRocks())
    }

    fun getMockedCategories(count: Int = 9): List<CategoryPresentableListItem> =
        mutableListOf<CategoryPresentableListItem>().apply {
            repeat(count) {
                val randomColor = Color.argb(255, Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))
                val item = CategoryPresentableListItem(
                    id = it.toLong() + 1,
                    name = "kategorie $it",
                    color = randomColor
                )
                add(item)
            }
        }

    fun getMockedRocks(count: Int = 9): List<RockPresentableListItem> =
        mutableListOf<RockPresentableListItem>().apply {
            repeat(count) {
                val randomColor = Color.argb(255, Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))
                val item = RockPresentableListItem(
                    id = it.toLong() + 1,
                    name = "Superšutr",
                    color = randomColor,
                    categoryId = (it % 2 + 1).toLong(),
                    comment = "commeeeeeeeent",
                    count = 2,
                    date = LocalDate.of(2020,10,10),
                    description = "descriptiooooooon",
                    folderPath = "some/path/probably/with/rock/id",
                    from = "from wherever",
                    latitude = 55.55555,
                    longitude = 44.4444,
                    locality = "locaaaalityyyy",
                    where = "somewhere",
                    pictureName = "awdawda."
                )
                add(item)
            }
        }

    private fun createRockFolders(rocks: List<RockPresentableListItem>) {
        val sutralogDirectory = File(sutralogPath)
        sutralogDirectory.mkdirs()

        rocks.forEach {
            val stoneDirectory = File(it.folderPath)
            stoneDirectory.mkdirs()
        }
    }
}