package com.gensee.multi_instance

import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import com.gensee.common.GenseeConfig
import com.gensee.multi_instance.ui.DemoInitParam
import com.gensee.multi_instance.ui.page.AddItemPage
import com.gensee.multi_instance.ui.page.GuidePage
import com.gensee.multi_instance.ui.page.SettingPage
import com.gensee.multi_instance.ui.theme.MultiinstanceDemoTheme
import com.gensee.multi_instance.ui.viewmodel.InitParamsViewModel
import com.gensee.vod.VodSite
import com.tencent.bugly.crashreport.CrashReport
import kotlinx.coroutines.launch
import java.util.ArrayList

class MainActivity : ComponentActivity() {
    private val TAG = "MainActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        GenseeConfig.isForceFlv = false
//        GenseeConfig.isPVHardDecode = false

        CrashReport.initCrashReport(this,"3c3de5bba8",true)
//                CrashReport.testNativeCrash()
        setContent {
            MainUI(modifier = Modifier.fillMaxSize())
        }
//        requestPermissions()


    }

}


@OptIn(ExperimentalFoundationApi::class)
//@Preview(showBackground = true)
@Composable
fun MainUI(modifier: Modifier = Modifier, initParamsViewModel: InitParamsViewModel = viewModel()) {
    val pagerState = rememberPagerState(pageCount = {
        3
    })
    val context = LocalContext.current
    // 恢复数据
    initParamsViewModel.restore(context)
    val coroutineScope = rememberCoroutineScope()


    MultiinstanceDemoTheme (){
        Surface(modifier) {
            Box(modifier = Modifier.fillMaxWidth()) {
                HorizontalPager(state = pagerState, userScrollEnabled = false,) {
//                    progress.value = pagerState.currentPage / pagerState.pageCount.toFloat()
//                    Log.i("TAG", "MainUI: " + pagerState.currentPage)
                    when (it) {
                        0 -> {
                            GuidePage(onClick ={
                                coroutineScope.launch {
                                    // Call scroll to on pagerState
                                    pagerState.animateScrollToPage(pagerState.currentPage + 1)
                                }
                            })
                        }
                        1 -> {
                            AddItemPage(last = {
                                coroutineScope.launch {
                                    // Call scroll to on pagerState
                                    pagerState.animateScrollToPage(pagerState.currentPage - 1)
                                }
                            }, next = {
                                coroutineScope.launch {
                                    // Call scroll to on pagerState
                                    pagerState.animateScrollToPage(pagerState.currentPage + 1)
                                }
                            })
                        }
                        2 -> {
                            SettingPage(last = {
                                coroutineScope.launch {
                                    // Call scroll to on pagerState
                                    pagerState.animateScrollToPage(pagerState.currentPage - 1)
                                }
                            }, next = {

                                coroutineScope.launch {
                                    if (pagerState.currentPage == pagerState.pageCount - 1) {

//                                        val value = initParamsViewModel.videoInfoList
                                        val value = extractEnableList(initParamsViewModel.videoInfoList)
                                        if (value.isEmpty()) {
                                            return@launch
                                        }
                                        if (!GenseeConfig.isMultiPlayer && value.size != 1) {
                                            Toast.makeText(context,"单实例模式不允许播放多个",Toast.LENGTH_SHORT).show()
                                            return@launch
                                        }
                                        VodSite.init(context,null)
                                        val intent = Intent(context, PageActivity::class.java)
                                        intent.putExtra("list",value as ArrayList<out Parcelable>)
                                        context.startActivity(intent)
                                    } else {
                                        pagerState.animateScrollToPage(pagerState.currentPage + 1)
                                    }

                                }
                            })
                        }
                    }

                }
//                LinearProgressIndicator(
//                    progress = (pagerState.currentPage + 1) / pagerState.pageCount.toFloat(),
//                    modifier = Modifier
//                        .fillMaxWidth()
//                        .align(Alignment.BottomCenter),
//                )
                MyIndicator((pagerState.currentPage + 1) / pagerState.pageCount.toFloat(),
                    modifier = Modifier
                        .fillMaxWidth()
                        .align(Alignment.BottomCenter))
            }


        }

    }
}

private fun extractEnableList(videoInfoList: List<DemoInitParam>):ArrayList<DemoInitParam>{
    val newList = arrayListOf<DemoInitParam>()
    videoInfoList.forEach {
        if (it.enable) {
            newList.add(it)
        }
    }
    return newList
}

@Composable
fun MyIndicator(indicatorProgress: Float,modifier:Modifier) {
    var progress by remember { mutableStateOf(0f) }
    val progressAnimDuration = 500
    val progressAnimation by animateFloatAsState(
        targetValue = indicatorProgress,
//        animationSpec = tween(durationMillis = progressAnimDuration)
    )
    LinearProgressIndicator(
        progress = progressAnimation,
        modifier = modifier,
    )
    LaunchedEffect(indicatorProgress) {
        progress = indicatorProgress
    }
}


