- package com.example.aifbmekpi
- import android.app.appsearch.SearchResult
- import android.content.Context
- import android.content.SharedPreferences
- import android.graphics.Movie
- import android.graphics.fonts.FontFamily
- import android.os.*
- import android.util.DisplayMetrics
- import android.util.Log
- import android.view.Gravity
- import android.view.View
- import android.view.WindowManager
- import android.widget.Toast
- import android.widget.Toolbar
- import androidx.activity.ComponentActivity
- import androidx.activity.compose.setContent
- import androidx.compose.animation.animateColor
- import androidx.compose.animation.animateColorAsState
- import androidx.compose.animation.core.updateTransition
- import androidx.compose.foundation.Image
- import androidx.compose.foundation.background
- import androidx.compose.foundation.border
- import androidx.compose.foundation.horizontalScroll
- import androidx.compose.foundation.layout.*
- import androidx.compose.foundation.lazy.LazyColumn
- import androidx.compose.foundation.lazy.items
- import androidx.compose.foundation.shape.CircleShape
- import androidx.compose.foundation.shape.RoundedCornerShape
- import androidx.compose.material.*
- import androidx.compose.material.icons.Icons
- import androidx.compose.material.icons.filled.*
- import androidx.compose.material.icons.materialIcon
- import androidx.compose.runtime.*
- import androidx.compose.runtime.saveable.rememberSaveable
- import androidx.compose.runtime.snapshots.SnapshotStateList
- import androidx.compose.ui.Alignment
- import androidx.compose.ui.Modifier
- import androidx.compose.ui.draw.clip
- import androidx.compose.ui.geometry.Size
- import androidx.compose.ui.graphics.Color
- import androidx.compose.ui.graphics.Color.Companion.Green
- import androidx.compose.ui.graphics.Color.Companion.White
- import androidx.compose.ui.graphics.Color.Companion.Yellow
- import androidx.compose.ui.graphics.Outline
- import androidx.compose.ui.graphics.Path
- import androidx.compose.ui.graphics.Shape
- import androidx.compose.ui.layout.ContentScale
- import androidx.compose.ui.layout.onSizeChanged
- import androidx.compose.ui.platform.LocalContext
- import androidx.compose.ui.res.colorResource
- import androidx.compose.ui.res.painterResource
- import androidx.compose.ui.semantics.Role.Companion.Image
- import androidx.compose.ui.text.font.FontFamily.Companion.Serif
- import androidx.compose.ui.text.font.FontWeight
- import androidx.compose.ui.text.style.TextAlign
- import androidx.compose.ui.tooling.preview.Preview
- import androidx.compose.ui.unit.*
- import androidx.core.view.ViewCompat
- import androidx.core.view.WindowCompat
- import com.example.aifbmekpi.ui.theme.AIFBMEKPITheme
- import com.google.accompanist.insets.*
- import com.google.gson.Gson
- import com.google.gson.reflect.TypeToken
- import java.lang.NullPointerException
- import java.lang.NumberFormatException
- import java.text.SimpleDateFormat
- import java.util.*
- import kotlin.collections.ArrayList
- import kotlin.reflect.typeOf
- class MainActivity : ComponentActivity() {
- var messages = mutableStateListOf<ChatItem>()
- override fun onStop() {
- super.onStop()
- val sharedPreferences = getSharedPreferences("AIFBMEKPI", Context.MODE_PRIVATE)
- val prefsEditor = sharedPreferences.edit();
- val gson = Gson()
- val mess : List<ChatItem> = messages
- val json = gson.toJson(mess);
- prefsEditor.putString("chatHistory", json);
- prefsEditor.apply();
- }
- @ExperimentalMaterialApi
- @ExperimentalAnimatedInsets
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
- WindowCompat.setDecorFitsSystemWindows(window, false)
- val sharedPreferences = getSharedPreferences("AIFBMEKPI", Context.MODE_PRIVATE)
- val gson = Gson()
- val json = sharedPreferences.getString("chatHistory", "")
- val type = object: TypeToken<List<ChatItem>>() {}.type
- if(json != "") {
- val messTemp = gson.fromJson<List<ChatItem>>(json, type)
- messages.addAll(messTemp)
- }
- setContent {
- AIFBMEKPITheme {
- ProvideWindowInsets(windowInsetsAnimationsEnabled = true) {
- // A surface container using the 'background' color from the theme
- Surface(color = MaterialTheme.colors.background) {
- MainContent(messages, sharedPreferences = sharedPreferences)
- }
- }
- }
- }
- }
- }
- @ExperimentalMaterialApi
- @Composable
- fun MainContent(messages: MutableList<ChatItem>, sharedPreferences: SharedPreferences){
- var userState = remember { mutableStateOf(sharedPreferences.getString("userState", "Start").toString()) }
- var text by rememberSaveable { mutableStateOf("") }
- var botNameText by rememberSaveable { mutableStateOf(sharedPreferences.getString("botName", "Anna").toString()) }
- var userName = rememberSaveable { mutableStateOf(sharedPreferences.getString("userName", "друже").toString()) }
- var totalPairs = rememberSaveable { mutableStateOf(sharedPreferences.getInt("totalPairs", 0).toInt()) }
- val openDialog = remember { mutableStateOf(false) }
- val context = LocalContext.current
- var onlineStatus = remember {
- mutableStateOf("was online resently")
- }
- val scaffoldState = rememberScaffoldState(rememberDrawerState(DrawerValue.Closed))
- val scope = rememberCoroutineScope()
- //val navController = rememberNavController()
- val result = remember { mutableStateOf("") }
- val expanded = remember { mutableStateOf(false)}
- val liked = remember { mutableStateOf(true) }
- val bottomAppBarHeight = remember {
- mutableStateOf(0.dp)
- }
- //sendMessage(messages = messages, userState = userState)
- if(userState.value=="Start"){
- userState.value = "TypingStart"
- Handler().postDelayed(Runnable {
- //anything you want to start after 3s
- onlineStatus.value = "Online"
- Handler().postDelayed(Runnable {
- onlineStatus.value="Typing..."
- Handler().postDelayed(Runnable {
- onlineStatus.value="Online"
- if (userState.value=="TypingStart") {
- userState.value = "Name"
- val editor = sharedPreferences.edit()
- editor.putString("userState", userState.value)
- editor.apply()
- val askForNameMess = ChatItem(
- sender = false,
- text = "Привіт! мене звати $botNameText. А як звати тебе?"
- )
- messages.add(askForNameMess)
- vibratePhone(context)
- Handler().postDelayed(Runnable {
- val sdf = SimpleDateFormat("HH:mm")
- val currentDate = sdf.format(Date())
- if (userState.value == "Name")
- onlineStatus.value = "Was online at $currentDate"
- }, 2000)
- }
- }, 3000)
- }, 1000)
- }, 1000)
- }
- Scaffold(
- topBar = {
- TopAppBar(
- title = {
- Row() {
- Column(modifier = Modifier
- .wrapContentWidth()
- .fillMaxHeight(), verticalArrangement = Arrangement.Center) {
- Image(
- painter = painterResource(R.mipmap.img),
- contentDescription = "avatar",
- contentScale = ContentScale.FillWidth, // crop the image if it's not a square
- modifier = Modifier
- .size(50.dp)
- .clip(CircleShape)
- // clip to the circle shape
- // add a border (optional)
- )
- }
- Column(modifier = Modifier
- .padding(start = 10.dp, top = 0.dp, bottom = 0.dp, end = 0.dp)
- .fillMaxHeight()
- .wrapContentWidth()) {
- Text(text = botNameText, fontSize = 20.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Justify)
- Text(text = onlineStatus.value, fontSize=(15.sp), textAlign = TextAlign.Center, fontWeight = FontWeight.Normal)
- }
- }
- },
- navigationIcon = {
- IconButton(onClick = {
- }) {
- Icon(Icons.Filled.Menu, "")
- }
- },
- actions = {
- Box(
- ) {
- IconButton(onClick = {
- expanded.value = true
- }) {
- Icon(
- Icons.Filled.MoreVert,
- contentDescription = "Localized description"
- )
- }
- DropdownMenu(
- expanded = expanded.value,
- onDismissRequest = { expanded.value = false },
- ) {
- DropdownMenuItem(onClick = {
- expanded.value = false
- messages.clear()
- totalPairs.value = 0
- userState.value = "TypingClear"
- Handler().postDelayed(Runnable {
- //anything you want to start after 3s
- onlineStatus.value = "Online"
- Handler().postDelayed(Runnable {
- onlineStatus.value="Typing..."
- Handler().postDelayed(Runnable {
- onlineStatus.value="Online"
- if (userState.value=="TypingClear") {
- userState.value = "Name"
- val editor = sharedPreferences.edit()
- editor.putString("userState", userState.value)
- editor.apply()
- val askForNameMess = ChatItem(
- sender = false,
- text = "Привіт! мене звати $botNameText. А як звати тебе?"
- )
- messages.add(askForNameMess)
- vibratePhone(context)
- Handler().postDelayed(Runnable {
- val sdf = SimpleDateFormat("HH:mm")
- val currentDate = sdf.format(Date())
- if (userState.value == "Name")
- onlineStatus.value =
- "Was online at $currentDate"
- }, 2000)
- }
- }, 3000)
- }, 1000)
- }, 1000)
- }) {
- Text("Clear history")
- }
- DropdownMenuItem(onClick = {
- expanded.value = false
- openDialog.value = true
- }) {
- Text("Change bot name")
- }
- DropdownMenuItem(onClick = {
- expanded.value = false
- }) {
- Row() {
- Text(text = "Message pairs")
- BadgeBox(badgeContent = { Text(text = "${totalPairs.value}")}, backgroundColor = colorResource(R.color.purple_500)) {
- }
- }
- }
- }
- }
- },
- backgroundColor = Color(0xFD1F4E03),
- elevation = AppBarDefaults.TopAppBarElevation,
- modifier = Modifier.statusBarsPadding()
- )
- },
- content = {
- Column(
- modifier = Modifier.navigationBarsPadding()
- ) {
- val paddings = PaddingValues(start = 0.dp, top=15.dp, end = 0.dp, bottom = bottomAppBarHeight.value)
- LazyColumn(reverseLayout = true, contentPadding = paddings,modifier = Modifier
- .fillMaxHeight()
- .fillMaxWidth()
- .navigationBarsWithImePadding()
- ){
- items(messages.reversed()){
- message-> MessageItem(message = message)
- }
- }
- }
- } ,
- bottomBar = {
- BottomAppBar(backgroundColor = Color.DarkGray, modifier = Modifier.navigationBarsWithImePadding()) {
- var animColor by remember { mutableStateOf(true) }
- val sendColor by animateColorAsState(if (animColor) White else Green)
- Box(modifier = Modifier
- .fillMaxSize()
- ) {
- TextField(
- value = text,
- label = {Text("Enter message")},
- onValueChange = {
- text = it
- },
- colors = TextFieldDefaults.outlinedTextFieldColors(
- focusedBorderColor = colorResource(R.color.purple_500),
- focusedLabelColor= colorResource(R.color.purple_500),
- cursorColor = colorResource(R.color.purple_500),
- unfocusedBorderColor = Yellow),
- modifier = Modifier
- .fillMaxWidth(1f)
- .onSizeChanged {
- bottomAppBarHeight.value = it.height.pixelsToDp(context).dp
- }
- )
- IconButton(onClick = {
- if(text!="") {
- val newMess = ChatItem(text = text, sender = true)
- messages.add(newMess)
- /*TODO*/
- val old_text = text
- text = ""
- when (userState.value) {
- "Name" -> {
- totalPairs.value=totalPairs.value+1
- val editor = sharedPreferences.edit()
- editor.putString("userName", old_text)
- editor.putInt("totalPairs", totalPairs.value)
- userName.value = old_text
- editor.apply()
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Приємно познайомитися, $old_text \uD83D\uDE0A", "А скільки тобі років?"),
- messageState = "Name",
- nextState = "Age",
- context = context
- )
- }
- "Time" -> {
- totalPairs.value=totalPairs.value+1
- val editor = sharedPreferences.edit()
- editor.putInt("totalPairs", totalPairs.value)
- editor.apply()
- val sdf = SimpleDateFormat("HH")
- val currentDate = sdf.format(Date()).toInt()
- if(currentDate >= 6 && currentDate < 12){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Який морозний сьогодні ранок..."),
- messageState = "Time",
- nextState = "Age",
- context = context
- )
- } else if(currentDate >= 12 && currentDate < 18){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Скоріше б вже вечір..."),
- messageState = "Time",
- nextState = "Age",
- context = context
- )
- } else if(currentDate >= 18 && currentDate < 23){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Який чудовий вечір! Думаю подивтись фільм Великий Гетсбі..."),
- messageState = "Time",
- nextState = "Age",
- context = context
- )
- } else if(currentDate >= 23 && currentDate < 6){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Вже так пізно, пора б лягати спати..."),
- messageState = "Time",
- nextState = "Age",
- context = context
- )
- }
- }
- "Music" -> {
- totalPairs.value=totalPairs.value+1
- val editor = sharedPreferences.edit()
- editor.putInt("totalPairs", totalPairs.value)
- editor.apply()
- if(old_text=="Так" || old_text== "так"){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Круто... Я люблю Вівальді. Ти чув 'Пори року'?"),
- messageState = "Music",
- nextState = "YearTimes",
- context = context
- )
- } else if (old_text=="Ні" ||old_text=="ні"){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Хм, шкода, а я дуже люблю Вівальді, особливо 'Пори року'. Мені здається, що тобі б сподобалось... А кіно ти любиш?"),
- messageState = "Music",
- nextState = "Cinema",
- context = context
- )
- }else if (old_text=="Ні" ||old_text=="ні"){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Вибач, я тебе не зрозуміла..."),
- messageState = "Music",
- nextState = "Music",
- context = context
- )
- }
- }
- "YearTimes" -> {
- totalPairs.value=totalPairs.value+1
- val editor = sharedPreferences.edit()
- editor.putInt("totalPairs", totalPairs.value)
- editor.apply()
- if(old_text=="Так" || old_text== "так"){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Вау! Дуже класно, що ти захоплюєшся такими речами. А кіно ти любиш?"),
- messageState = "YearTimes",
- nextState = "Cinema",
- context = context
- )
- } else if (old_text=="Ні" ||old_text=="ні"){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Хм, шкода, мені здається, що тобі б сподобалось... А кіно ти любиш?"),
- messageState = "YearTimes",
- nextState = "Cinema",
- context = context
- )
- }else{
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Вибач, я тебе не зрозуміла..."),
- messageState = "YearTimes",
- nextState = "YearTimes",
- context = context
- )
- }
- }
- "Cinema" -> {
- totalPairs.value=totalPairs.value+1
- val editor = sharedPreferences.edit()
- editor.putInt("totalPairs", totalPairs.value)
- editor.apply()
- if(old_text=="Так" || old_text== "так"){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Я теж люблю. Мій найулюблініший жанр - комедія. А який твій улюблініший жанр?"),
- messageState = "Cinema",
- nextState = "Genre",
- context = context
- )
- } else if (old_text=="Ні" ||old_text=="ні"){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Шкода( я дивлюсь багато фільмів у вільний час. Ще у вільний час я люблю гуляти. Скільки годин ти зазвичай гуляєш?"),
- messageState = "Cinema",
- nextState = "Walking",
- context = context
- )
- }else {
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Вибач, я тебе не зрозуміла..."),
- messageState = "Cinema",
- nextState = "Cinema",
- context = context
- )
- }
- }
- "Genre" -> {
- totalPairs.value=totalPairs.value+1
- val editor = sharedPreferences.edit()
- editor.putInt("totalPairs", totalPairs.value)
- editor.apply()
- if(old_text=="комедія" || old_text== "Комедія"){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Ух, класно, що в нас співпадають вкуси. Я також люблю гуляти. Скільки годин ти зазвичай гуляєш?"),
- messageState = "Genre",
- nextState = "Walking",
- context = context
- )
- } else {
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("$old_text мені також подобається... Я також люблю гуляти. Скільки годин ти зазвичай гуляєш?"),
- messageState = "Genre",
- nextState = "Walking",
- context = context
- )
- }
- }
- "Age" -> {
- try {
- totalPairs.value=totalPairs.value+1
- val editor = sharedPreferences.edit()
- editor.putInt("totalPairs", totalPairs.value)
- editor.apply()
- if (old_text.toInt() < 15) {
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf(
- "Зрозуміло...",
- "То ти ще малий) Тоді розкажу тобі казку",
- "Летіла ворона понад морем, дивиться — лізе рак. Вона хап його та й понесла через лиман у ліс, щоб, сівши де-небудь на гіллі, гарненько поснідати. Бачить рак, що приходиться пропасти, та й каже вороні: «Ей, вороно, вороно, знав я твого батька і твою матір: славні люди були!»—«Угу!»—каже ворона, не роззявляючи рота. «І братів, і сестер твоїх знав,— каже рак,— що за добрі люди були!» — «Угу!» — гугнить ворона, а рака кріпенько держить. «Та вже хоч вони і гарні люди,— каже рак,— а тобі не рівня. Мені здається, що й на світі нема розумнішої над тебе!» —«Еге!»—крикнула ворона на весь рот і впустила рака в море.\n" +
- "\n" +
- "От тим-то, як кого одурять хвалою або улесливою річчю, то люди й кажуть: «Упустив рака з рота». А як кого остерігають, то кажуть: «Гляди, не впусти рака з рота»."
- ,"Слухай, ${userName.value}, ти любиш класичну музику?"),
- messageState = "Age",
- nextState = "Music",
- context = context
- )
- } else if (old_text.toInt()< 30){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf(
- "Круто!",
- "Розкажу тобі анекдот",
- "1 монітор - звичайний програміст, 2 монітори - просунутий програміст, 3 монітори - системний адміністратор, 4 монітори - охоронець"
- , "Слухай, ${userName.value}, ти любиш класичну музику?"),
- messageState = "Age",
- nextState = "Music",
- context = context
- )
- } else {
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf(
- "Ого... Можу тобі порадити ліки від суглобів - альмірал або альфорт",
- "Слухай, ${userName.value}, ти любиш класичну музику?"
- ),
- messageState = "Age",
- nextState = "Music",
- context = context
- )
- }
- } catch (e: NumberFormatException){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf(
- "${userName.value}, будь ласка, напиши свій вік числом",
- ),
- messageState = "Age",
- nextState = "Age",
- context = context
- )
- }
- }
- "Walking" -> {
- try {
- totalPairs.value=totalPairs.value+1
- val editor = sharedPreferences.edit()
- editor.putInt("totalPairs", totalPairs.value)
- editor.apply()
- val sdf = SimpleDateFormat("HH")
- val currentDate = sdf.format(Date()).toInt()
- var buyMessage = "mess"
- if(currentDate >= 6 && currentDate < 12){
- buyMessage ="Який морозний сьогодні ранок... Мені час збиратись на роботу, приємно було поспілкуватися!"
- } else if(currentDate >= 12 && currentDate < 18){
- buyMessage ="Слухай, я зараз на роботі, відповім пізніше"
- } else if(currentDate >= 18 && currentDate < 23){
- buyMessage ="Який чудовий вечір! Думаю подивитись фільм Великий Гетсбі... Так що спишимось пізніше, бувай"
- } else if(currentDate >= 23 || currentDate < 6){
- buyMessage ="Вже так пізно, пора лягати спати... До зустрічі!"
- }
- if (old_text.toInt() < 0) {
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Ойой... схоже ти не людина....", buyMessage),
- messageState = "Walking",
- nextState = "Sleep",
- context = context
- )
- } else if (old_text.toInt()==0){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Слухай, це погано, бувати на чистому повітрі дуже необхідно", buyMessage),
- messageState = "Walking",
- nextState = "Sleep",
- context = context
- )
- } else if (old_text.toInt()==1){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Хм, мабуть треба намагатися гуляти більше, я проводжу на вулиці мінімум по 2-3 години", buyMessage),
- messageState = "Walking",
- nextState = "Sleep",
- context = context
- )
- }else if (old_text.toInt()<4){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Класс! це дуже потрібно і круто, що ти приділяєш цьому увагу", buyMessage),
- messageState = "Walking",
- nextState = "Sleep",
- context = context
- )
- }else {
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf("Та ти шо!!! Дуже дуже круто, так тримати))", buyMessage),
- messageState = "Walking",
- nextState = "Sleep",
- context = context
- )
- }
- } catch (e: NumberFormatException){
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf(
- "${userName.value}, будь ласка, напиши скільки годин ти гуляєш числом",
- ),
- messageState = "Walking",
- nextState = "Walking",
- context = context
- )
- }
- }
- "Sleep" -> {
- totalPairs.value=totalPairs.value+1
- val editor = sharedPreferences.edit()
- editor.putInt("totalPairs", totalPairs.value)
- editor.apply()
- val sdf = SimpleDateFormat("HH")
- val currentDate = sdf.format(Date()).toInt()
- var buyMessage = "${userName.value}, я зараз на роботі, відповім пізніше"
- if(currentDate >= 6 && currentDate < 12){
- buyMessage ="${userName.value}, я зараз збираюсь на роботу, відповім пізніше"
- } else if(currentDate >= 12 && currentDate < 18){
- buyMessage ="${userName.value}, я зараз на роботі, відповім пізніше"
- } else if(currentDate >= 18 && currentDate < 23){
- buyMessage ="${userName.value}, я зараз дивлюсь фільм, відповім пізніше"
- } else if(currentDate >= 23 || currentDate < 6){
- buyMessage ="${userName.value}, я сплю, відповім пізніше"
- }
- SendMessage(
- messages = messages,
- userState = userState,
- onlineStatus = onlineStatus,
- sharedPreferences = sharedPreferences,
- texts = listOf(buyMessage),
- messageState = "Sleep",
- nextState = "Sleep",
- context = context
- )
- }
- }
- }
- },modifier = Modifier.align(Alignment.CenterEnd)) {
- val transition = updateTransition(animColor, label="Indicator")
- val tint by transition.animateColor(label = "Tint") {
- animColor->
- if (animColor) White else Green
- }
- Icon(Icons.Filled.Send, contentDescription = "send", tint=White)
- }
- }
- }
- },
- drawerContent = {
- Column(modifier = Modifier.systemBarsPadding()) {
- Text(text = "123312313")
- Text(text = "123312313")
- Text(text = "123312313")
- }})
- if (openDialog.value) {
- AlertDialog(
- onDismissRequest = {
- // Dismiss the dialog when the user clicks outside the dialog or on the back
- // button. If you want to disable that functionality, simply use an empty
- // onCloseRequest.
- openDialog.value = false
- },
- text = {
- OutlinedTextField(label = {Text("Bot name")}, value = botNameText, onValueChange = {botNameText = it}, colors = TextFieldDefaults.outlinedTextFieldColors(
- focusedBorderColor = colorResource(R.color.purple_500),
- focusedLabelColor= colorResource(R.color.purple_500),
- cursorColor = colorResource(R.color.purple_500),
- unfocusedBorderColor = Yellow))
- },
- confirmButton = {
- Button(
- onClick = {
- openDialog.value = false
- val editor = sharedPreferences.edit()
- editor.putString("botName", botNameText)
- editor.apply()
- },
- Modifier
- .padding(15.dp)
- .background(colorResource(R.color.purple_500))) {
- Text("Save")
- }
- },
- shape = RoundedCornerShape(15.dp)
- )
- }
- }
- fun Int.pixelsToDp(context: Context):Float{
- return this / (context.resources
- .displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT).toFloat()
- }
- @Composable
- fun MessageItem(message: ChatItem){
- if (message.sender){
- Row(
- Modifier
- .height(IntrinsicSize.Max)
- .padding(horizontal = 10.dp, vertical = 2.dp)
- .fillMaxWidth(), horizontalArrangement = Arrangement.End) {
- Column(
- modifier = Modifier
- .background(
- color = colorResource(R.color.purple_500),
- shape = RoundedCornerShape(6.dp, 6.dp, 0.dp, 6.dp)
- )
- .wrapContentWidth()
- ) {
- Text(message.text, modifier = Modifier.padding(5.dp))
- }
- Column(
- modifier = Modifier
- .background(
- color = colorResource(R.color.purple_500),
- shape = TriangleEdgeShapeUser(10)
- )
- .width(10.dp)
- .fillMaxHeight()
- ) {
- }
- }
- } else {
- Row(
- Modifier
- .height(IntrinsicSize.Max)
- .padding(horizontal = 10.dp, vertical = 2.dp)
- .fillMaxWidth()) {
- Column(
- modifier = Modifier
- .background(
- color = colorResource(R.color.purple_700),
- shape = TriangleEdgeShapeBot(10)
- )
- .width(8.dp)
- .fillMaxHeight()
- ) {
- }
- Column(
- modifier = Modifier
- .background(
- color = colorResource(R.color.purple_700),
- shape = RoundedCornerShape(6.dp, 6.dp, 6.dp, 0.dp)
- )
- .wrapContentWidth()
- ) {
- Text(message.text, modifier = Modifier.padding(5.dp))
- }
- }
- }
- }
- @Preview(showBackground = true)
- @Composable
- fun DefaultPreview() {
- AIFBMEKPITheme {
- }
- }
- data class ChatItem(
- val sender: Boolean,
- val text: String
- )
- class TriangleEdgeShapeUser(val offset: Int) : Shape {
- override fun createOutline(
- size: Size,
- layoutDirection: LayoutDirection,
- density: Density
- ): Outline {
- val trianglePath = Path().apply {
- moveTo(x = 0f, y = size.height-offset)
- lineTo(x = 0f, y = size.height)
- lineTo(x = 0f + offset, y = size.height)
- }
- return Outline.Generic(path = trianglePath)
- }
- }
- class TriangleEdgeShapeBot(val offset: Int) : Shape {
- override fun createOutline(
- size: Size,
- layoutDirection: LayoutDirection,
- density: Density
- ): Outline {
- val trianglePath = Path().apply {
- moveTo(x = size.width, y = size.height-offset)
- lineTo(x = size.width, y = size.height)
- lineTo(x = size.width-offset, y = size.height)
- }
- return Outline.Generic(path = trianglePath)
- }
- }
- fun SendMessage(messages: MutableList<ChatItem>, userState: MutableState<String>, onlineStatus: MutableState<String>, sharedPreferences: SharedPreferences, messageState: String, nextState: String, context: Context, texts: List<String>){
- userState.value = "Typing$messageState"
- Handler().postDelayed(Runnable {
- //anything you want to start after 3s
- if (onlineStatus.value != "Typing...")
- onlineStatus.value = "Online"
- Handler().postDelayed(Runnable {
- SendMessagePart(messages, userState, onlineStatus, sharedPreferences, messageState, nextState, context, texts)
- //anything you want to start after 3s
- }, 1000)
- }, 1000)
- }
- fun SendMessagePart(messages: MutableList<ChatItem>, userState: MutableState<String>, onlineStatus: MutableState<String>, sharedPreferences: SharedPreferences, messageState: String, nextState: String, context: Context, texts: List<String>){
- onlineStatus.value = "Typing..."
- Handler().postDelayed(Runnable {
- //anything you want to start after 3s
- onlineStatus.value = "Online"
- if (userState.value == "Typing$messageState") {
- val botMess =
- ChatItem(
- sender = false,
- text = texts[0]
- )
- messages.add(botMess)
- vibratePhone(context = context)
- if (texts.size==1){
- userState.value = nextState
- val editor = sharedPreferences.edit()
- editor.putString("userState", userState.value)
- editor.apply()
- Handler().postDelayed(Runnable {
- //anything you want to start after 3s
- val sdf = SimpleDateFormat("HH:mm")
- val currentDate = sdf.format(Date())
- if (userState.value == nextState)
- onlineStatus.value =
- "Was online at $currentDate"
- }, 2000)
- } else{
- SendMessagePart(messages = messages, userState, onlineStatus, sharedPreferences, messageState, nextState, context, texts=texts.slice(1..texts.size-1))
- }
- }
- }, 2000)
- }
- fun vibratePhone(context: Context) {
- val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
- if (Build.VERSION.SDK_INT >= 26) {
- vibrator.vibrate(VibrationEffect.createOneShot(50, VibrationEffect.DEFAULT_AMPLITUDE))
- } else {
- vibrator.vibrate(200)
- }
- }
[text] чел
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
Editor
You can edit this paste and save as new: