package com.example.modifier.ui.settings

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.example.modifier.Global
import com.example.modifier.Utils
import com.example.modifier.http.KtorClient
import com.example.modifier.http.response.RcsNumberResponse
import com.example.modifier.model.TelephonyConfig
import io.ktor.client.call.body
import io.ktor.client.request.put
import io.ktor.http.ContentType
import io.ktor.http.contentType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.apache.commons.lang3.RandomStringUtils

class SettingsViewModel : ViewModel() {
    private val TAG = "SettingsViewModel"

    suspend fun requestNumber() {
        val response = KtorClient.put("/api/rcs-number") {
            contentType(ContentType.Application.Json)
        }
        val rcsRes = response.body<RcsNumberResponse>()
        Log.i(TAG, "response: $rcsRes")

        Global.save(
            TelephonyConfig(
                rcsRes.number,
                rcsRes.mcc,
                rcsRes.mnc,
                Global.genICCID(rcsRes.mnc, rcsRes.areaCode),
                rcsRes.mcc + rcsRes.mnc + RandomStringUtils.randomNumeric(
                    15 - rcsRes.mcc.length - rcsRes.mnc.length
                ),
                Utils.generateIMEI(),
                rcsRes.country,
                rcsRes.areaCode
            )
        )

        liveData(Dispatchers.IO) {
            viewModelScope.launch {
                Runtime.getRuntime().exec("su -c \"logcat -c\"")
                Runtime.getRuntime().exec("su -c logcat")
                    .inputStream
                    .bufferedReader()
                    .useLines { lines ->
                        lines.forEach { line -> emit(line) }
                    }
            }
        }


    }
}