package com.convenient.android.lib.ui.sample.read

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.*
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.lifecycleScope
import com.compdfkit.core.document.CPDFDocument
import com.compdfkit.ui.reader.CPDFReaderView
import com.compdfkit.ui.reader.IReaderViewCallback
import com.convenient.android.common.utils.ToastUtil
import com.convenient.android.lib.ui.sample.read.setting.BottomSettingView
import com.convenient.android.lib.ui.theme.SampleTheme
import com.pdf.base.function.documentIsEncrypt
import com.pdf.base.function.openDocument
import com.pdf.base.function.retryOpenDocument
import kotlinx.coroutines.launch

/**
 * @author: hubowen
 * @date: 2022/9/20
 * @description:
 */
var readerView: CPDFReaderView? = null

class ReaderActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            SampleTheme {
                readerPage(lifecycleScope)
            }
        }
    }
}

@Preview(showSystemUi = true)
@Composable
fun MainPagePreview() {
    SampleTheme {
        readerPage(null)
    }
}

@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter", "CoroutineCreationDuringComposition")
@Composable
fun readerPage(life: LifecycleCoroutineScope?) {
    val context = LocalContext.current

    val coroutineScope = rememberCoroutineScope()

    var currentDocument by remember { mutableStateOf<CPDFDocument?>(null) }

    val choosePDFFileLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.OpenMultipleDocuments(), onResult = {
        //第一个文件
        when (it.isNotEmpty()) {
            true -> it[0].apply {
                life?.launch {

                    if (context.documentIsEncrypt(this@apply)) {
                        Log.e("AAAA", "文档已加密")
                    }else{
                        Log.e("AAAA", "文档未加密")
                    }

                    context.openDocument(this@apply, "", ""){

                        success {
                            currentDocument = it
                        }

                        fail {
                            Log.e("AAAA", "初始化失败")
                        }

                        isEncrypt {
                            ToastUtil.showToast(context, "文档已加密")
                            life.launch {
                                it.retryOpenDocument(this@apply, absolutePath = "", password = "", normalOpenDocumentCallback = this@openDocument)
                            }
                        }
                    }
                }
            }
            else -> ToastUtil.showToast(context, "初始化失败")
        }
    })

    val sheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
    ModalBottomSheetLayout(
        modifier = Modifier.fillMaxSize(),
        sheetState = sheetState,
        sheetContent = {
            BottomSettingView()
        }) {
        Column {
            Scaffold(
                modifier = Modifier.fillMaxSize(),
                topBar = {
                    SmallTopAppBar(
                        title = {
                            Text(text = "ReadView", style = androidx.compose.material3.MaterialTheme.typography.titleMedium)
                        },
                        colors = TopAppBarDefaults.smallTopAppBarColors(
                            containerColor = androidx.compose.material3.MaterialTheme.colorScheme.primary.copy(alpha = .1F)
                        ),
                        actions = {
                            IconButton(onClick = {
                                coroutineScope.launch {
                                    sheetState.show()
                                }
                            }) {
                                Icon(Icons.Filled.Settings, null)
                            }
                            IconButton(onClick = {
                                choosePDFFileLauncher.launch(arrayOf("*/*"))
                            }) {
                                Icon(Icons.Filled.Add, null)
                            }
                        }
                    )
                }
            ) {
                Column(modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight(Alignment.CenterVertically)) {
                    //ReaderView展示位置
                    AndroidView(factory = { context ->
                        CPDFReaderView(context).apply {
                            readerView = this
                            //监听设置
                            setReaderViewCallback(object : IReaderViewCallback {
                                override fun onTapMainDocArea() {
                                    Log.e("AAAA", "onTapMainDocArea")
                                }

                                override fun onMoveToChild(p0: Int) {
                                }

                                override fun onEndScroll() {
                                }

                                override fun onScrolling() {
                                }

                                override fun onRecordLastJumpPageNum(p0: Int) {
                                    Log.e("AAAA", "onRecordLastJumpPageNum")
                                }
                            })
                        }
                    }, update = { readerView ->
                        readerView.pdfDocument = currentDocument
                        readerView.reloadPages()
                    }, modifier = Modifier
                        .fillMaxWidth()
                        .fillMaxHeight())
                }
            }
        }
    }
}