package com.youdao.zhiyun.compositiondemo

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.provider.OpenableColumns
import android.util.Base64
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.youdao.zhiyun.compositiondemo.databinding.ActivityChineseImageBinding
import com.youdao.compositioncorrection.CompositionCorrection
import com.youdao.compositioncorrection.CorrectListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.Serializable

class ChineseImageActivity : AppCompatActivity() {
    val TAG ="ChineseImageActivity"

    val grades = arrayOf(
        "一年级",
        "二年纪",
        "三年纪",
        "四年纪",
        "五年纪",
        "六年纪",
        "初一",
        "初二",
        "初三",
        "高一",
        "高二",
        "高三"
    )
    val gradeMap = mapOf(
        "一年级" to "g1",
        "二年纪" to "g2",
        "三年纪" to "g3",
        "四年纪" to "g4",
        "五年纪" to "g5",
        "六年纪" to "g6",
        "初一" to "g7",
        "初二" to "g8",
        "初三" to "g9",
        "高一" to "g10",
        "高二" to "g11",
        "高三" to "g12"
    )
    private  var grade =""
    private val MAX_SIZE = 1.5f * 1024 * 1024
    private lateinit var binding: ActivityChineseImageBinding
    private  var imageBase64:String =""
    val EN_TEXT_TEST_DATA ="""The most meaningful activity I took part in at school When I was a Junior 3 student, I was very shy. I wasn't brave enough to take part in any school activities. But when I became a Junior 4 student, an activity changed my personalities. As a Junior 4 student, I felt I was under great stress. But this stress didn't stop me from thinking to attend the biggist activity in our school. Because of my shy personality, I hesitated for many times. But at last, in order to realize my statge dream, I took part in the activity. I performed very well for I knew it was the last time I could attend. I was surprised at how brave I was that time. Sometimes, one person want to succeed in doing one thing, then, he must be brave, or he must fail."""
    val CH_TEXT_TEST_DATA ="""月亮有时变成一个大大的圆，像一个大圆盘，又像一个圆圆的大月饼，还像一面圆圆的镜子。我多想飞到月亮上，坐在“大圆盘”上，看看这个“大圆盘”到底有多大；我又想坐在这个“大圆盘”上，咬一口“月饼”，看看它到底有多香；我还想抱着这个“大镜子”，照一照宇宙到底有多大。"""

    @SuppressLint("Range")
    val getImage =   registerForActivityResult(ActivityResultContracts.GetContent()){ fullPhotoUri ->
        fullPhotoUri?.let {
            Log.d(TAG, "onActivityResult: fullPhotoUri: ${fullPhotoUri.path} ")
            val cursor = contentResolver.query(it, null, null, null, null)
            cursor?.let {
                if (it.moveToFirst()) {
                    it.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                    val fileSize =  it.getString(cursor.getColumnIndex(OpenableColumns.SIZE)).toLong()
                    Log.e(TAG, "fileSize: $fileSize")
                    if (fileSize > MAX_SIZE ){
                        Toast.makeText(this@ChineseImageActivity, "图片不可以超过1.5M", Toast.LENGTH_SHORT).show()
                        return@registerForActivityResult
                    }

                }
            }


            val  thumbnail = BitmapFactory.decodeStream(contentResolver.openInputStream(fullPhotoUri))
            binding.imageCorrect.setImageBitmap(thumbnail)
            lifecycleScope.launch(Dispatchers.IO) {
                val baos = ByteArrayOutputStream()
                val quality = 100
                thumbnail.compress(Bitmap.CompressFormat.JPEG, quality, baos)
                val datas = baos.toByteArray()
                imageBase64 = Base64.encodeToString(datas, 2)
                Log.e(TAG, "onActivityResult: imageBase64:${imageBase64.length}")
                withContext(Dispatchers.Main){
                binding.button3.isEnabled = true
                    binding.btnGuide.isEnabled = true
                }
            }
        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityChineseImageBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initGradeSpSpinner()
    }
    private fun initGradeSpSpinner() {
        binding.spGrade.apply {
            prompt = "请选择作文等级"
            adapter = ArrayAdapter<String>(this@ChineseImageActivity, R.layout.item_grade, grades)
            setSelection(0)
            grade = gradeMap[grades[0]].toString()
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
                override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) {
                    Toast.makeText(this@ChineseImageActivity, "${grades[position]}", Toast.LENGTH_SHORT).show()
                    grade = gradeMap[grades[position]].toString()
                    Log.d("ChineseImageActivity", "onItemSelected:$grade ")
                }

                override fun onNothingSelected(p0: AdapterView<*>?) {
                }

            }
        }

    }
    fun correct(view: View) {

        val title = if ( binding.etTitle.text.toString().isEmpty() )null else binding.etTitle.text.toString()
        val requirement = if ( binding.etRequirement.text.toString().isEmpty() )null else binding.etRequirement.text.toString()
//        CompositionCorrectioner.correctionEnglishText(input = EN_TEXT_TEST_DATA,
        CompositionCorrection.correctionChineseImage(
            input =imageBase64,
            listener= object :CorrectListener{
                override fun onError(errorCode: Int?, msg: String?, requestId: String?) {
                    Log.e(TAG, "onError:  errorCode:$errorCode,msg:$msg,requestId:$requestId", )
                }

                override fun onResult(result: Serializable, requestId: String) {
                    runOnUiThread {
                        startActivity(Intent(this@ChineseImageActivity,CorrectResultActivity::class.java).apply {
                            putExtra("result",result as Serializable)
                            putExtra("type","ch_image")
                        })
                    }
                }

            },
            grade = grade,
            title = title,
            requirement= requirement,
        )
        binding.button3.isEnabled = false
        binding.btnGuide.isEnabled = false
        lifecycleScope.launch{
            withContext(Dispatchers.Main){
                binding.tvResult.text ="sfhd"
                binding.button3.isEnabled = true
                binding.btnGuide.isEnabled = true
            }
        }
    }

    fun guide(view: View) {
        val title = if ( binding.etTitle.text.toString().isEmpty() )null else binding.etTitle.text.toString()
        val requirement = if ( binding.etRequirement.text.toString().isEmpty() )null else binding.etRequirement.text.toString()
        CompositionCorrection.guideChineseImage(
            input =imageBase64,
            listener= object :CorrectListener{
                override fun onError(errorCode: Int?, msg: String?, requestId: String?) {
                    Log.e(TAG, "onError:  errorCode:$errorCode,msg:$msg,requestId:$requestId", )
                }
                override fun onResult(result: Serializable, requestId: String) {
                    runOnUiThread {
                        startActivity(Intent(this@ChineseImageActivity,CorrectResultActivity::class.java).apply {
                            putExtra("result",result as Serializable)
                            putExtra("type","ch_image_guidance")
                        })
                    }
                }
            },
        )
        binding.button3.isEnabled = false
        binding.btnGuide.isEnabled = false
        lifecycleScope.launch{
            withContext(Dispatchers.Main){
                binding.tvResult.text ="sfhd"
                binding.button3.isEnabled = true
                binding.btnGuide.isEnabled = true
            }
        }
    }

    fun chooseImage(view: View) {
        getImage.launch("image/*")
    }
}