[text] чел

Viewer

  1. package com.example.aifbmekpi
  2.  
  3. import android.app.appsearch.SearchResult
  4. import android.content.Context
  5. import android.content.SharedPreferences
  6. import android.graphics.Movie
  7. import android.graphics.fonts.FontFamily
  8. import android.os.*
  9. import android.util.DisplayMetrics
  10. import android.util.Log
  11. import android.view.Gravity
  12. import android.view.View
  13. import android.view.WindowManager
  14. import android.widget.Toast
  15. import android.widget.Toolbar
  16. import androidx.activity.ComponentActivity
  17. import androidx.activity.compose.setContent
  18. import androidx.compose.animation.animateColor
  19. import androidx.compose.animation.animateColorAsState
  20. import androidx.compose.animation.core.updateTransition
  21. import androidx.compose.foundation.Image
  22. import androidx.compose.foundation.background
  23. import androidx.compose.foundation.border
  24. import androidx.compose.foundation.horizontalScroll
  25. import androidx.compose.foundation.layout.*
  26. import androidx.compose.foundation.lazy.LazyColumn
  27. import androidx.compose.foundation.lazy.items
  28. import androidx.compose.foundation.shape.CircleShape
  29. import androidx.compose.foundation.shape.RoundedCornerShape
  30. import androidx.compose.material.*
  31. import androidx.compose.material.icons.Icons
  32. import androidx.compose.material.icons.filled.*
  33. import androidx.compose.material.icons.materialIcon
  34. import androidx.compose.runtime.*
  35. import androidx.compose.runtime.saveable.rememberSaveable
  36. import androidx.compose.runtime.snapshots.SnapshotStateList
  37. import androidx.compose.ui.Alignment
  38. import androidx.compose.ui.Modifier
  39. import androidx.compose.ui.draw.clip
  40. import androidx.compose.ui.geometry.Size
  41. import androidx.compose.ui.graphics.Color
  42. import androidx.compose.ui.graphics.Color.Companion.Green
  43. import androidx.compose.ui.graphics.Color.Companion.White
  44. import androidx.compose.ui.graphics.Color.Companion.Yellow
  45. import androidx.compose.ui.graphics.Outline
  46. import androidx.compose.ui.graphics.Path
  47. import androidx.compose.ui.graphics.Shape
  48. import androidx.compose.ui.layout.ContentScale
  49. import androidx.compose.ui.layout.onSizeChanged
  50. import androidx.compose.ui.platform.LocalContext
  51. import androidx.compose.ui.res.colorResource
  52. import androidx.compose.ui.res.painterResource
  53. import androidx.compose.ui.semantics.Role.Companion.Image
  54. import androidx.compose.ui.text.font.FontFamily.Companion.Serif
  55. import androidx.compose.ui.text.font.FontWeight
  56. import androidx.compose.ui.text.style.TextAlign
  57. import androidx.compose.ui.tooling.preview.Preview
  58. import androidx.compose.ui.unit.*
  59. import androidx.core.view.ViewCompat
  60. import androidx.core.view.WindowCompat
  61. import com.example.aifbmekpi.ui.theme.AIFBMEKPITheme
  62. import com.google.accompanist.insets.*
  63. import com.google.gson.Gson
  64. import com.google.gson.reflect.TypeToken
  65. import java.lang.NullPointerException
  66. import java.lang.NumberFormatException
  67. import java.text.SimpleDateFormat
  68. import java.util.*
  69. import kotlin.collections.ArrayList
  70. import kotlin.reflect.typeOf
  71.  
  72.  
  73. class MainActivity : ComponentActivity() {
  74.  
  75.  
  76.     var messages = mutableStateListOf<ChatItem>()
  77.  
  78.     override fun onStop() {
  79.         super.onStop()
  80.         val sharedPreferences = getSharedPreferences("AIFBMEKPI", Context.MODE_PRIVATE)
  81.         val prefsEditor = sharedPreferences.edit();
  82.         val gson =  Gson()
  83.         val mess : List<ChatItem> = messages
  84.  
  85.  
  86.         val json = gson.toJson(mess);
  87.         prefsEditor.putString("chatHistory", json);
  88.  
  89.         prefsEditor.apply();
  90.  
  91.  
  92.     }
  93.  
  94.  
  95.     @ExperimentalMaterialApi
  96.     @ExperimentalAnimatedInsets
  97.     override fun onCreate(savedInstanceState: Bundle?) {
  98.         super.onCreate(savedInstanceState)
  99.         window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
  100.         WindowCompat.setDecorFitsSystemWindows(window, false)
  101.  
  102.         val sharedPreferences = getSharedPreferences("AIFBMEKPI", Context.MODE_PRIVATE)
  103.         val gson = Gson()
  104.         val json = sharedPreferences.getString("chatHistory", "")
  105.         val type = object: TypeToken<List<ChatItem>>() {}.type
  106.  
  107.         if(json != "") {
  108.  
  109.             val messTemp = gson.fromJson<List<ChatItem>>(json, type)
  110.  
  111.  
  112.  
  113.             messages.addAll(messTemp)
  114.  
  115.     }
  116.         setContent {
  117.             AIFBMEKPITheme {
  118.                 ProvideWindowInsets(windowInsetsAnimationsEnabled = true) {
  119.                     // A surface container using the 'background' color from the theme
  120.                     Surface(color = MaterialTheme.colors.background) {
  121.  
  122.                         MainContent(messages, sharedPreferences = sharedPreferences)
  123.                     }
  124.  
  125.                 }
  126.             }
  127.  
  128.  
  129.         }
  130.  
  131.  
  132.     }
  133. }
  134.  
  135.  
  136.  
  137. @ExperimentalMaterialApi
  138. @Composable
  139. fun MainContent(messages: MutableList<ChatItem>, sharedPreferences: SharedPreferences){
  140.     var userState = remember { mutableStateOf(sharedPreferences.getString("userState", "Start").toString()) }
  141.     var text by rememberSaveable { mutableStateOf("") }
  142.     var botNameText by rememberSaveable { mutableStateOf(sharedPreferences.getString("botName", "Anna").toString()) }
  143.     var userName = rememberSaveable { mutableStateOf(sharedPreferences.getString("userName", "друже").toString()) }
  144.     var totalPairs = rememberSaveable { mutableStateOf(sharedPreferences.getInt("totalPairs", 0).toInt()) }
  145.     val openDialog = remember { mutableStateOf(false)  }
  146.     val context = LocalContext.current
  147.     var onlineStatus = remember {
  148.         mutableStateOf("was online resently")
  149.     }
  150.     val scaffoldState = rememberScaffoldState(rememberDrawerState(DrawerValue.Closed))
  151.     val scope = rememberCoroutineScope()
  152.     //val navController = rememberNavController()
  153.     val result = remember { mutableStateOf("") }
  154.     val expanded = remember { mutableStateOf(false)}
  155.     val liked = remember { mutableStateOf(true) }
  156.     val bottomAppBarHeight  = remember {
  157.         mutableStateOf(0.dp)
  158.     }
  159.  
  160.         //sendMessage(messages = messages, userState = userState)
  161.  
  162.     if(userState.value=="Start"){
  163.         userState.value = "TypingStart"
  164.  
  165.         Handler().postDelayed(Runnable {
  166.             //anything you want to start after 3s
  167.  
  168.  
  169.             onlineStatus.value = "Online"
  170.             Handler().postDelayed(Runnable {
  171.                 onlineStatus.value="Typing..."
  172.  
  173.                 Handler().postDelayed(Runnable {
  174.                     onlineStatus.value="Online"
  175.                     if (userState.value=="TypingStart") {
  176.                         userState.value = "Name"
  177.                         val editor = sharedPreferences.edit()
  178.                         editor.putString("userState", userState.value)
  179.                         editor.apply()
  180.                         val askForNameMess = ChatItem(
  181.                             sender = false,
  182.                             text = "Привіт! мене звати $botNameText. А як звати тебе?"
  183.                         )
  184.                         messages.add(askForNameMess)
  185.                         vibratePhone(context)
  186.                         Handler().postDelayed(Runnable {
  187.                             val sdf = SimpleDateFormat("HH:mm")
  188.                             val currentDate = sdf.format(Date())
  189.                             if (userState.value == "Name")
  190.                                 onlineStatus.value = "Was online at $currentDate"
  191.                         }, 2000)
  192.                     }
  193.  
  194.                 }, 3000)
  195.  
  196.             }, 1000)
  197.  
  198.         }, 1000)
  199.     }
  200.     Scaffold(
  201.         topBar = {
  202.             TopAppBar(
  203.                 title = {
  204.                     Row() {
  205.                         Column(modifier = Modifier
  206.                             .wrapContentWidth()
  207.                             .fillMaxHeight(), verticalArrangement = Arrangement.Center) {
  208.                             Image(
  209.                                 painter = painterResource(R.mipmap.img),
  210.                                 contentDescription = "avatar",
  211.  
  212.                                 contentScale = ContentScale.FillWidth,            // crop the image if it's not a square
  213.                                 modifier = Modifier
  214.                                     .size(50.dp)
  215.                                     .clip(CircleShape)
  216.                                     // clip to the circle shape
  217.                                        // add a border (optional)
  218.                             )
  219.                         }
  220.  
  221.                         Column(modifier = Modifier
  222.                             .padding(start = 10.dp, top = 0.dp, bottom = 0.dp, end = 0.dp)
  223.                             .fillMaxHeight()
  224.                             .wrapContentWidth()) {
  225.                             Text(text = botNameText, fontSize = 20.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Justify)
  226.                             Text(text = onlineStatus.value, fontSize=(15.sp), textAlign = TextAlign.Center, fontWeight = FontWeight.Normal)
  227.                         }
  228.  
  229.                     }
  230.  
  231.                 },
  232.                 navigationIcon = {
  233.                     IconButton(onClick = {
  234.                         
  235.                     }) {
  236.                         Icon(Icons.Filled.Menu, "")
  237.                     }
  238.                 },
  239.  
  240.  
  241.                 actions = {
  242.  
  243.  
  244.  
  245.  
  246.                     Box(
  247.  
  248.                     ) {
  249.                         IconButton(onClick = {
  250.                             expanded.value = true
  251.  
  252.                         }) {
  253.                             Icon(
  254.                                 Icons.Filled.MoreVert,
  255.                                 contentDescription = "Localized description"
  256.                             )
  257.                         }
  258.  
  259.                         DropdownMenu(
  260.                             expanded = expanded.value,
  261.                             onDismissRequest = { expanded.value = false },
  262.                         ) {
  263.                             DropdownMenuItem(onClick = {
  264.                                 expanded.value = false
  265.                                 messages.clear()
  266.                                 totalPairs.value = 0
  267.                                 userState.value = "TypingClear"
  268.                                 Handler().postDelayed(Runnable {
  269.                                     //anything you want to start after 3s
  270.  
  271.  
  272.                                     onlineStatus.value = "Online"
  273.                                     Handler().postDelayed(Runnable {
  274.                                         onlineStatus.value="Typing..."
  275.  
  276.                                         Handler().postDelayed(Runnable {
  277.                                         onlineStatus.value="Online"
  278.                                             if (userState.value=="TypingClear") {
  279.                                                 userState.value = "Name"
  280.                                                 val editor = sharedPreferences.edit()
  281.                                                 editor.putString("userState", userState.value)
  282.                                                 editor.apply()
  283.                                                 val askForNameMess = ChatItem(
  284.                                                     sender = false,
  285.                                                     text = "Привіт! мене звати $botNameText. А як звати тебе?"
  286.                                                 )
  287.                                                 messages.add(askForNameMess)
  288.                                                 vibratePhone(context)
  289.                                                 Handler().postDelayed(Runnable {
  290.                                                     val sdf = SimpleDateFormat("HH:mm")
  291.                                                     val currentDate = sdf.format(Date())
  292.                                                     if (userState.value == "Name")
  293.                                                         onlineStatus.value =
  294.                                                             "Was online at $currentDate"
  295.                                                 }, 2000)
  296.  
  297.                                             }
  298.                                         }, 3000)
  299.  
  300.                                     }, 1000)
  301.  
  302.                                 }, 1000)
  303.                             }) {
  304.                                 Text("Clear history")
  305.                             }
  306.                             DropdownMenuItem(onClick = {
  307.                                 expanded.value = false
  308.                                 openDialog.value = true
  309.  
  310.                             }) {
  311.                                 Text("Change bot name")
  312.                             }
  313.                             DropdownMenuItem(onClick = {
  314.                                 expanded.value = false
  315.  
  316.  
  317.                             }) {
  318.                                 Row() {
  319.                                     Text(text = "Message pairs")
  320.                                     BadgeBox(badgeContent = { Text(text = "${totalPairs.value}")}, backgroundColor = colorResource(R.color.purple_500)) {
  321.  
  322.                                     }
  323.                                 }
  324.  
  325.                             }
  326.  
  327.  
  328.                         }
  329.                     }
  330.                 },
  331.  
  332.                 backgroundColor = Color(0xFD1F4E03),
  333.                 elevation = AppBarDefaults.TopAppBarElevation,
  334.                 modifier = Modifier.statusBarsPadding()
  335.             )
  336.         },
  337.  
  338.         content = {
  339.             Column(
  340.                 modifier = Modifier.navigationBarsPadding()
  341.             ) {
  342.                 val paddings = PaddingValues(start = 0.dp, top=15.dp, end = 0.dp, bottom = bottomAppBarHeight.value)
  343.                 LazyColumn(reverseLayout = true, contentPadding = paddings,modifier = Modifier
  344.                     .fillMaxHeight()
  345.                     .fillMaxWidth()
  346.                     .navigationBarsWithImePadding()
  347.  
  348.                      ){
  349.  
  350.         items(messages.reversed()){
  351.     message-> MessageItem(message = message)
  352.                     }
  353.  
  354.                 }
  355.  
  356.             }
  357.         } ,
  358.         bottomBar = {
  359.             BottomAppBar(backgroundColor = Color.DarkGray, modifier = Modifier.navigationBarsWithImePadding()) {
  360.  
  361.                 var animColor by remember { mutableStateOf(true) }
  362.  
  363.                 val sendColor by animateColorAsState(if (animColor) White else Green)
  364.  
  365.                 Box(modifier = Modifier
  366.                     .fillMaxSize()
  367.                     ) {
  368.                     TextField(
  369.                         value = text,
  370.  
  371.                         label = {Text("Enter message")},
  372.                         onValueChange = {
  373.                             text = it
  374.                         },
  375.  
  376.  
  377.                         colors = TextFieldDefaults.outlinedTextFieldColors(
  378.                             focusedBorderColor = colorResource(R.color.purple_500),
  379.                             focusedLabelColor= colorResource(R.color.purple_500),
  380.                             cursorColor = colorResource(R.color.purple_500),
  381.                                     unfocusedBorderColor = Yellow),
  382.  
  383.                         modifier = Modifier
  384.                             .fillMaxWidth(1f)
  385.                             .onSizeChanged {
  386.  
  387.                                 bottomAppBarHeight.value = it.height.pixelsToDp(context).dp
  388.  
  389.                             }
  390.                     )
  391.                     IconButton(onClick = {
  392.                         if(text!="") {
  393.                             val newMess = ChatItem(text = text, sender = true)
  394.                             messages.add(newMess)
  395.                             /*TODO*/
  396.                             val old_text = text
  397.                             text = ""
  398.  
  399.                             when (userState.value) {
  400.                                 "Name" -> {
  401.                                     totalPairs.value=totalPairs.value+1
  402.  
  403.                                     val editor = sharedPreferences.edit()
  404.                                     editor.putString("userName", old_text)
  405.                                     editor.putInt("totalPairs", totalPairs.value)
  406.                                     userName.value = old_text
  407.                                     editor.apply()
  408.                                     SendMessage(
  409.                                         messages = messages,
  410.                                         userState = userState,
  411.                                         onlineStatus = onlineStatus,
  412.                                         sharedPreferences = sharedPreferences,
  413.                                         texts = listOf("Приємно познайомитися, $old_text \uD83D\uDE0A", "А скільки тобі років?"),
  414.                                         messageState = "Name",
  415.                                         nextState = "Age",
  416.                                         context = context
  417.                                     )
  418.  
  419.                                 }
  420.  
  421.                                 "Time" -> {
  422.                                     totalPairs.value=totalPairs.value+1
  423.  
  424.                                     val editor = sharedPreferences.edit()
  425.  
  426.                                     editor.putInt("totalPairs", totalPairs.value)
  427.  
  428.                                     editor.apply()
  429.                                     val sdf = SimpleDateFormat("HH")
  430.  
  431.  
  432.                                     val currentDate = sdf.format(Date()).toInt()
  433.                                     if(currentDate >= 6 && currentDate < 12){
  434.                                         SendMessage(
  435.                                             messages = messages,
  436.                                             userState = userState,
  437.                                             onlineStatus = onlineStatus,
  438.                                             sharedPreferences = sharedPreferences,
  439.                                             texts = listOf("Який морозний сьогодні ранок..."),
  440.                                             messageState = "Time",
  441.                                             nextState = "Age",
  442.                                             context = context
  443.                                         )
  444.                                     } else if(currentDate >= 12 && currentDate < 18){
  445.                                         SendMessage(
  446.                                             messages = messages,
  447.                                             userState = userState,
  448.                                             onlineStatus = onlineStatus,
  449.                                             sharedPreferences = sharedPreferences,
  450.                                             texts = listOf("Скоріше б вже вечір..."),
  451.                                             messageState = "Time",
  452.                                             nextState = "Age",
  453.                                             context = context
  454.                                         )
  455.                                     } else if(currentDate >= 18 && currentDate < 23){
  456.                                         SendMessage(
  457.                                             messages = messages,
  458.                                             userState = userState,
  459.                                             onlineStatus = onlineStatus,
  460.                                             sharedPreferences = sharedPreferences,
  461.                                             texts = listOf("Який чудовий вечір! Думаю подивтись фільм Великий Гетсбі..."),
  462.                                             messageState = "Time",
  463.                                             nextState = "Age",
  464.                                             context = context
  465.                                         )
  466.                                     } else if(currentDate >= 23 && currentDate < 6){
  467.                                         SendMessage(
  468.                                             messages = messages,
  469.                                             userState = userState,
  470.                                             onlineStatus = onlineStatus,
  471.                                             sharedPreferences = sharedPreferences,
  472.                                             texts = listOf("Вже так пізно, пора б лягати спати..."),
  473.                                             messageState = "Time",
  474.                                             nextState = "Age",
  475.                                             context = context
  476.                                         )
  477.                                     }
  478.  
  479.  
  480.                                 }
  481.                                 "Music" -> {
  482.                                     totalPairs.value=totalPairs.value+1
  483.  
  484.                                     val editor = sharedPreferences.edit()
  485.  
  486.                                     editor.putInt("totalPairs", totalPairs.value)
  487.  
  488.                                     editor.apply()
  489.  
  490.  
  491.                                     if(old_text=="Так" || old_text== "так"){
  492.                                         SendMessage(
  493.                                             messages = messages,
  494.                                             userState = userState,
  495.                                             onlineStatus = onlineStatus,
  496.                                             sharedPreferences = sharedPreferences,
  497.                                             texts = listOf("Круто... Я люблю Вівальді. Ти чув 'Пори року'?"),
  498.                                             messageState = "Music",
  499.                                             nextState = "YearTimes",
  500.                                             context = context
  501.                                         )
  502.                                     } else if (old_text=="Ні" ||old_text=="ні"){
  503.                                         SendMessage(
  504.                                             messages = messages,
  505.                                             userState = userState,
  506.                                             onlineStatus = onlineStatus,
  507.                                             sharedPreferences = sharedPreferences,
  508.                                             texts = listOf("Хм, шкода, а я дуже люблю Вівальді, особливо 'Пори року'. Мені здається, що тобі б сподобалось... А кіно ти любиш?"),
  509.                                             messageState = "Music",
  510.                                             nextState = "Cinema",
  511.                                             context = context
  512.                                         )
  513.                                     }else if (old_text=="Ні" ||old_text=="ні"){
  514.                                         SendMessage(
  515.                                             messages = messages,
  516.                                             userState = userState,
  517.                                             onlineStatus = onlineStatus,
  518.                                             sharedPreferences = sharedPreferences,
  519.                                             texts = listOf("Вибач, я тебе не зрозуміла..."),
  520.                                             messageState = "Music",
  521.                                             nextState = "Music",
  522.                                             context = context
  523.                                         )
  524.                                     }
  525.  
  526.  
  527.  
  528.                                 }
  529.                                 "YearTimes" -> {
  530.                                     totalPairs.value=totalPairs.value+1
  531.  
  532.                                     val editor = sharedPreferences.edit()
  533.  
  534.                                     editor.putInt("totalPairs", totalPairs.value)
  535.  
  536.                                     editor.apply()
  537.  
  538.  
  539.                                     if(old_text=="Так" || old_text== "так"){
  540.                                         SendMessage(
  541.                                             messages = messages,
  542.                                             userState = userState,
  543.                                             onlineStatus = onlineStatus,
  544.                                             sharedPreferences = sharedPreferences,
  545.                                             texts = listOf("Вау! Дуже класно, що ти захоплюєшся такими речами. А кіно ти любиш?"),
  546.                                             messageState = "YearTimes",
  547.                                             nextState = "Cinema",
  548.                                             context = context
  549.                                         )
  550.                                     } else if (old_text=="Ні" ||old_text=="ні"){
  551.                                         SendMessage(
  552.                                             messages = messages,
  553.                                             userState = userState,
  554.                                             onlineStatus = onlineStatus,
  555.                                             sharedPreferences = sharedPreferences,
  556.                                             texts = listOf("Хм, шкода, мені здається, що тобі б сподобалось... А кіно ти любиш?"),
  557.                                             messageState = "YearTimes",
  558.                                             nextState = "Cinema",
  559.                                             context = context
  560.                                         )
  561.                                     }else{
  562.                                         SendMessage(
  563.                                             messages = messages,
  564.                                             userState = userState,
  565.                                             onlineStatus = onlineStatus,
  566.                                             sharedPreferences = sharedPreferences,
  567.                                             texts = listOf("Вибач, я тебе не зрозуміла..."),
  568.                                             messageState = "YearTimes",
  569.                                             nextState = "YearTimes",
  570.                                             context = context
  571.                                         )
  572.                                     }
  573.  
  574.  
  575.  
  576.                                 }
  577.                                 "Cinema" -> {
  578.                                     totalPairs.value=totalPairs.value+1
  579.  
  580.                                     val editor = sharedPreferences.edit()
  581.  
  582.                                     editor.putInt("totalPairs", totalPairs.value)
  583.  
  584.                                     editor.apply()
  585.  
  586.  
  587.                                     if(old_text=="Так" || old_text== "так"){
  588.                                         SendMessage(
  589.                                             messages = messages,
  590.                                             userState = userState,
  591.                                             onlineStatus = onlineStatus,
  592.                                             sharedPreferences = sharedPreferences,
  593.                                             texts = listOf("Я теж люблю. Мій найулюблініший жанр - комедія. А який твій улюблініший жанр?"),
  594.                                             messageState = "Cinema",
  595.                                             nextState = "Genre",
  596.                                             context = context
  597.                                         )
  598.                                     } else if (old_text=="Ні" ||old_text=="ні"){
  599.  
  600.                                         SendMessage(
  601.                                             messages = messages,
  602.                                             userState = userState,
  603.                                             onlineStatus = onlineStatus,
  604.                                             sharedPreferences = sharedPreferences,
  605.                                             texts = listOf("Шкода( я дивлюсь багато фільмів у вільний час. Ще у вільний час я люблю гуляти. Скільки годин ти зазвичай гуляєш?"),
  606.                                             messageState = "Cinema",
  607.                                             nextState = "Walking",
  608.                                             context = context
  609.                                         )
  610.                                     }else {
  611.  
  612.                                         SendMessage(
  613.                                             messages = messages,
  614.                                             userState = userState,
  615.                                             onlineStatus = onlineStatus,
  616.                                             sharedPreferences = sharedPreferences,
  617.                                             texts = listOf("Вибач, я тебе не зрозуміла..."),
  618.                                             messageState = "Cinema",
  619.                                             nextState = "Cinema",
  620.                                             context = context
  621.                                         )
  622.                                     }
  623.  
  624.  
  625.  
  626.                                 }
  627.                                 "Genre" -> {
  628.                                     totalPairs.value=totalPairs.value+1
  629.  
  630.                                     val editor = sharedPreferences.edit()
  631.  
  632.                                     editor.putInt("totalPairs", totalPairs.value)
  633.  
  634.                                     editor.apply()
  635.  
  636.  
  637.                                     if(old_text=="комедія" || old_text== "Комедія"){
  638.                                         SendMessage(
  639.                                             messages = messages,
  640.                                             userState = userState,
  641.                                             onlineStatus = onlineStatus,
  642.                                             sharedPreferences = sharedPreferences,
  643.                                             texts = listOf("Ух, класно, що в нас співпадають вкуси. Я також люблю гуляти. Скільки годин ти зазвичай гуляєш?"),
  644.                                             messageState = "Genre",
  645.                                             nextState = "Walking",
  646.                                             context = context
  647.                                         )
  648.                                     } else {
  649.  
  650.                                         SendMessage(
  651.                                             messages = messages,
  652.                                             userState = userState,
  653.                                             onlineStatus = onlineStatus,
  654.                                             sharedPreferences = sharedPreferences,
  655.                                             texts = listOf("$old_text мені також подобається... Я також люблю гуляти. Скільки годин ти зазвичай гуляєш?"),
  656.                                             messageState = "Genre",
  657.                                             nextState = "Walking",
  658.                                             context = context
  659.                                         )
  660.                                     }
  661.  
  662.  
  663.  
  664.                                 }
  665.                                 "Age" -> {
  666.                                     try {
  667.                                         totalPairs.value=totalPairs.value+1
  668.                                         val editor = sharedPreferences.edit()
  669.  
  670.                                         editor.putInt("totalPairs", totalPairs.value)
  671.  
  672.                                         editor.apply()
  673.                                         if (old_text.toInt() < 15) {
  674.                                             SendMessage(
  675.                                                 messages = messages,
  676.                                                 userState = userState,
  677.                                                 onlineStatus = onlineStatus,
  678.                                                 sharedPreferences = sharedPreferences,
  679.                                                 texts = listOf(
  680.                                                     "Зрозуміло...",
  681.                                                     "То ти ще малий) Тоді розкажу тобі казку",
  682.                                                     "Летіла ворона понад морем, дивиться — лізе рак. Вона хап його та й понесла через лиман у ліс, щоб, сівши де-небудь на гіллі, гарненько поснідати. Бачить рак, що приходиться пропасти, та й каже вороні: «Ей, вороно, вороно, знав я твого батька і твою матір: славні люди були!»—«Угу!»—каже ворона, не роззявляючи рота. «І братів, і сестер твоїх знав,— каже рак,— що за добрі люди були!» — «Угу!» — гугнить ворона, а рака кріпенько держить. «Та вже хоч вони і гарні люди,— каже рак,— а тобі не рівня. Мені здається, що й на світі нема розумнішої над тебе!» —«Еге!»—крикнула ворона на весь рот і впустила рака в море.\n" +
  683.                                                             "\n" +
  684.                                                             "От тим-то, як кого одурять хвалою або улесливою річчю, то люди й кажуть: «Упустив рака з рота». А як кого остерігають, то кажуть: «Гляди, не впусти рака з рота»."
  685.                                                 ,"Слухай, ${userName.value}, ти любиш класичну музику?"),
  686.                                                 messageState = "Age",
  687.                                                 nextState = "Music",
  688.                                                 context = context
  689.                                             )
  690.                                         } else if (old_text.toInt()< 30){
  691.                                             SendMessage(
  692.                                                 messages = messages,
  693.                                                 userState = userState,
  694.                                                 onlineStatus = onlineStatus,
  695.                                                 sharedPreferences = sharedPreferences,
  696.                                                 texts = listOf(
  697.                                                     "Круто!",
  698.                                                     "Розкажу тобі анекдот",
  699.                                                     "1 монітор - звичайний програміст, 2 монітори - просунутий програміст, 3 монітори - системний адміністратор, 4 монітори - охоронець"
  700.                                                 , "Слухай, ${userName.value}, ти любиш класичну музику?"),
  701.                                                 messageState = "Age",
  702.                                                 nextState = "Music",
  703.                                                 context = context
  704.                                             )
  705.                                         } else {
  706.                                             SendMessage(
  707.                                                 messages = messages,
  708.                                                 userState = userState,
  709.                                                 onlineStatus = onlineStatus,
  710.                                                 sharedPreferences = sharedPreferences,
  711.                                                 texts = listOf(
  712.                                                     "Ого... Можу тобі порадити ліки від суглобів - альмірал або альфорт",
  713.                                                     "Слухай, ${userName.value}, ти любиш класичну музику?"
  714.                                                     ),
  715.                                                 messageState = "Age",
  716.                                                 nextState = "Music",
  717.                                                 context = context
  718.                                             )
  719.                                         }
  720.                                     } catch (e: NumberFormatException){
  721.                                         SendMessage(
  722.                                             messages = messages,
  723.                                             userState = userState,
  724.                                             onlineStatus = onlineStatus,
  725.                                             sharedPreferences = sharedPreferences,
  726.                                             texts = listOf(
  727.                                                 "${userName.value}, будь ласка, напиши свій вік числом",
  728.  
  729.                                                 ),
  730.                                             messageState = "Age",
  731.                                             nextState = "Age",
  732.                                             context = context
  733.                                         )
  734.                                     }
  735.  
  736.                                 }
  737.                                 "Walking" -> {
  738.                                     try {
  739.                                         totalPairs.value=totalPairs.value+1
  740.                                         val editor = sharedPreferences.edit()
  741.  
  742.                                         editor.putInt("totalPairs", totalPairs.value)
  743.  
  744.                                         editor.apply()
  745.                                         val sdf = SimpleDateFormat("HH")
  746.  
  747.  
  748.                                         val currentDate = sdf.format(Date()).toInt()
  749.                                         var buyMessage = "mess"
  750.                                         if(currentDate >= 6 && currentDate < 12){
  751.                                             buyMessage ="Який морозний сьогодні ранок... Мені час збиратись на роботу, приємно було поспілкуватися!"
  752.  
  753.                                         } else if(currentDate >= 12 && currentDate < 18){
  754.                                             buyMessage ="Слухай, я зараз на роботі, відповім пізніше"
  755.  
  756.                                         } else if(currentDate >= 18 && currentDate < 23){
  757.                                             buyMessage ="Який чудовий вечір! Думаю подивитись фільм Великий Гетсбі... Так що спишимось пізніше, бувай"
  758.  
  759.                                         } else if(currentDate >= 23 || currentDate < 6){
  760.                                             buyMessage ="Вже так пізно, пора лягати спати... До зустрічі!"
  761.  
  762.                                         }
  763.                                         if (old_text.toInt() < 0) {
  764.                                             SendMessage(
  765.                                                 messages = messages,
  766.                                                 userState = userState,
  767.                                                 onlineStatus = onlineStatus,
  768.                                                 sharedPreferences = sharedPreferences,
  769.                                                 texts = listOf("Ойой... схоже ти не людина....", buyMessage),
  770.                                                 messageState = "Walking",
  771.                                                 nextState = "Sleep",
  772.                                                 context = context
  773.                                             )
  774.                                         } else if (old_text.toInt()==0){
  775.                                             SendMessage(
  776.                                                 messages = messages,
  777.                                                 userState = userState,
  778.                                                 onlineStatus = onlineStatus,
  779.                                                 sharedPreferences = sharedPreferences,
  780.                                                 texts = listOf("Слухай, це погано, бувати на чистому повітрі дуже необхідно", buyMessage),
  781.                                                 messageState = "Walking",
  782.                                                 nextState = "Sleep",
  783.                                                 context = context
  784.                                             )
  785.                                         } else if (old_text.toInt()==1){
  786.                                             SendMessage(
  787.                                                 messages = messages,
  788.                                                 userState = userState,
  789.                                                 onlineStatus = onlineStatus,
  790.                                                 sharedPreferences = sharedPreferences,
  791.                                                 texts = listOf("Хм, мабуть треба намагатися гуляти більше, я проводжу на вулиці мінімум по 2-3 години", buyMessage),
  792.                                                 messageState = "Walking",
  793.                                                 nextState = "Sleep",
  794.                                                 context = context
  795.                                             )
  796.                                         }else if (old_text.toInt()<4){
  797.                                             SendMessage(
  798.                                                 messages = messages,
  799.                                                 userState = userState,
  800.                                                 onlineStatus = onlineStatus,
  801.                                                 sharedPreferences = sharedPreferences,
  802.                                                 texts = listOf("Класс! це дуже потрібно і круто, що ти приділяєш цьому увагу", buyMessage),
  803.                                                 messageState = "Walking",
  804.                                                 nextState = "Sleep",
  805.                                                 context = context
  806.                                             )
  807.                                         }else {
  808.                                             SendMessage(
  809.                                                 messages = messages,
  810.                                                 userState = userState,
  811.                                                 onlineStatus = onlineStatus,
  812.                                                 sharedPreferences = sharedPreferences,
  813.                                                 texts = listOf("Та ти шо!!! Дуже дуже круто, так тримати))", buyMessage),
  814.                                                 messageState = "Walking",
  815.                                                 nextState = "Sleep",
  816.                                                 context = context
  817.                                             )
  818.                                         }
  819.                                     } catch (e: NumberFormatException){
  820.                                         SendMessage(
  821.                                             messages = messages,
  822.                                             userState = userState,
  823.                                             onlineStatus = onlineStatus,
  824.                                             sharedPreferences = sharedPreferences,
  825.                                             texts = listOf(
  826.                                                 "${userName.value}, будь ласка, напиши скільки годин ти гуляєш числом",
  827.  
  828.                                                 ),
  829.                                             messageState = "Walking",
  830.                                             nextState = "Walking",
  831.                                             context = context
  832.                                         )
  833.                                     }
  834.  
  835.  
  836.  
  837.                                 }
  838.                                 "Sleep" -> {
  839.                                     totalPairs.value=totalPairs.value+1
  840.                                     val editor = sharedPreferences.edit()
  841.  
  842.                                     editor.putInt("totalPairs", totalPairs.value)
  843.  
  844.                                     editor.apply()
  845.                                     val sdf = SimpleDateFormat("HH")
  846.  
  847.  
  848.                                     val currentDate = sdf.format(Date()).toInt()
  849.                                     var buyMessage = "${userName.value}, я зараз на роботі, відповім пізніше"
  850.                                     if(currentDate >= 6 && currentDate < 12){
  851.                                         buyMessage ="${userName.value}, я зараз збираюсь на роботу, відповім пізніше"
  852.  
  853.                                     } else if(currentDate >= 12 && currentDate < 18){
  854.                                         buyMessage ="${userName.value}, я зараз на роботі, відповім пізніше"
  855.  
  856.                                     } else if(currentDate >= 18 && currentDate < 23){
  857.                                         buyMessage ="${userName.value}, я зараз дивлюсь фільм, відповім пізніше"
  858.  
  859.                                     } else if(currentDate >= 23 || currentDate < 6){
  860.                                         buyMessage ="${userName.value}, я сплю, відповім пізніше"
  861.  
  862.                                     }
  863.                                     SendMessage(
  864.                                         messages = messages,
  865.                                         userState = userState,
  866.                                         onlineStatus = onlineStatus,
  867.                                         sharedPreferences = sharedPreferences,
  868.                                         texts = listOf(buyMessage),
  869.                                         messageState = "Sleep",
  870.                                         nextState = "Sleep",
  871.                                         context = context
  872.                                     )
  873.  
  874.                                 }
  875.                                 
  876.                             }
  877.  
  878.  
  879.                         }
  880.  
  881.                                          },modifier = Modifier.align(Alignment.CenterEnd)) {
  882.                         val transition = updateTransition(animColor, label="Indicator")
  883.                         val tint by transition.animateColor(label = "Tint") {
  884.                             animColor->
  885.                             if (animColor) White else Green
  886.                         }
  887.                         Icon(Icons.Filled.Send, contentDescription = "send", tint=White)
  888.                     }
  889.                 }
  890.                 
  891.             }
  892.         },
  893.         drawerContent = {
  894.              Column(modifier = Modifier.systemBarsPadding()) {
  895.  
  896.                 Text(text = "123312313")
  897.                 Text(text = "123312313")
  898.                 Text(text = "123312313")
  899.             }})
  900.                 
  901.  
  902.  
  903.  
  904.     if (openDialog.value) {
  905.  
  906.         AlertDialog(
  907.             onDismissRequest = {
  908.                 // Dismiss the dialog when the user clicks outside the dialog or on the back
  909.                 // button. If you want to disable that functionality, simply use an empty
  910.                 // onCloseRequest.
  911.                 openDialog.value = false
  912.             },
  913.  
  914.             text = {
  915.                 OutlinedTextField(label = {Text("Bot name")}, value = botNameText, onValueChange = {botNameText = it}, colors = TextFieldDefaults.outlinedTextFieldColors(
  916.                     focusedBorderColor = colorResource(R.color.purple_500),
  917.                     focusedLabelColor= colorResource(R.color.purple_500),
  918.                     cursorColor = colorResource(R.color.purple_500),
  919.                     unfocusedBorderColor = Yellow))
  920.             },
  921.             confirmButton = {
  922.                 Button(
  923.  
  924.                     onClick = {
  925.                         openDialog.value = false
  926.                         val editor = sharedPreferences.edit()
  927.                         editor.putString("botName", botNameText)
  928.                         editor.apply()
  929.                     },
  930.                     Modifier
  931.                         .padding(15.dp)
  932.                         .background(colorResource(R.color.purple_500))) {
  933.                     Text("Save")
  934.                 }
  935.             },
  936.  
  937.  
  938.             shape = RoundedCornerShape(15.dp)
  939.         )
  940.     }
  941. }
  942.  
  943. fun Int.pixelsToDp(context: Context):Float{
  944.  
  945.     return this / (context.resources
  946.         .displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT).toFloat()
  947. }
  948.  
  949. @Composable
  950. fun MessageItem(message: ChatItem){
  951.     if (message.sender){
  952.     Row(
  953.         Modifier
  954.             .height(IntrinsicSize.Max)
  955.             .padding(horizontal = 10.dp, vertical = 2.dp)
  956.             .fillMaxWidth(), horizontalArrangement = Arrangement.End) {
  957.  
  958.         Column(
  959.             modifier = Modifier
  960.                 .background(
  961.                     color = colorResource(R.color.purple_500),
  962.                     shape = RoundedCornerShape(6.dp, 6.dp, 0.dp, 6.dp)
  963.                 )
  964.                 .wrapContentWidth()
  965.         ) {
  966.             Text(message.text, modifier = Modifier.padding(5.dp))
  967.         }
  968.         Column(
  969.             modifier = Modifier
  970.                 .background(
  971.                     color = colorResource(R.color.purple_500),
  972.                     shape = TriangleEdgeShapeUser(10)
  973.                 )
  974.                 .width(10.dp)
  975.                 .fillMaxHeight()
  976.         ) {
  977.  
  978.         }
  979.     }
  980.     } else {
  981.         Row(
  982.             Modifier
  983.                 .height(IntrinsicSize.Max)
  984.                 .padding(horizontal = 10.dp, vertical = 2.dp)
  985.                 .fillMaxWidth()) {
  986.             Column(
  987.                 modifier = Modifier
  988.                     .background(
  989.                         color = colorResource(R.color.purple_700),
  990.                         shape = TriangleEdgeShapeBot(10)
  991.                     )
  992.                     .width(8.dp)
  993.                     .fillMaxHeight()
  994.             ) {
  995.             }
  996.             Column(
  997.                 modifier = Modifier
  998.                     .background(
  999.                         color = colorResource(R.color.purple_700),
  1000.                         shape = RoundedCornerShape(6.dp, 6.dp, 6.dp, 0.dp)
  1001.                     )
  1002.                     .wrapContentWidth()
  1003.             ) {
  1004.                 Text(message.text, modifier = Modifier.padding(5.dp))
  1005.             }
  1006.         }
  1007.  
  1008.     }
  1009.  
  1010.  
  1011.  
  1012.  
  1013. }
  1014.  
  1015. @Preview(showBackground = true)
  1016. @Composable
  1017. fun DefaultPreview() {
  1018.     AIFBMEKPITheme {
  1019.  
  1020.     }
  1021. }
  1022.  
  1023. data class ChatItem(
  1024.     val sender: Boolean,
  1025.     val text: String
  1026. )
  1027.  
  1028.  
  1029. class TriangleEdgeShapeUser(val offset: Int) : Shape {
  1030.  
  1031.     override fun createOutline(
  1032.         size: Size,
  1033.         layoutDirection: LayoutDirection,
  1034.         density: Density
  1035.     ): Outline {
  1036.         val trianglePath = Path().apply {
  1037.             moveTo(x = 0f, y = size.height-offset)
  1038.             lineTo(x = 0f, y = size.height)
  1039.             lineTo(x = 0f + offset, y = size.height)
  1040.         }
  1041.         return Outline.Generic(path = trianglePath)
  1042.     }
  1043. }
  1044.  
  1045. class TriangleEdgeShapeBot(val offset: Int) : Shape {
  1046.  
  1047.     override fun createOutline(
  1048.         size: Size,
  1049.         layoutDirection: LayoutDirection,
  1050.         density: Density
  1051.     ): Outline {
  1052.         val trianglePath = Path().apply {
  1053.             moveTo(x = size.width, y = size.height-offset)
  1054.             lineTo(x = size.width, y = size.height)
  1055.             lineTo(x = size.width-offset, y = size.height)
  1056.         }
  1057.         return Outline.Generic(path = trianglePath)
  1058.     }
  1059. }
  1060.  
  1061.  
  1062.  
  1063. fun SendMessage(messages: MutableList<ChatItem>, userState: MutableState<String>, onlineStatus: MutableState<String>, sharedPreferences: SharedPreferences,  messageState: String, nextState: String, context: Context, texts: List<String>){
  1064.     userState.value = "Typing$messageState"
  1065.     Handler().postDelayed(Runnable {
  1066.         //anything you want to start after 3s
  1067.  
  1068.         if (onlineStatus.value != "Typing...")
  1069.             onlineStatus.value = "Online"
  1070.         Handler().postDelayed(Runnable {
  1071.             SendMessagePart(messages, userState, onlineStatus, sharedPreferences, messageState, nextState, context, texts)
  1072.  
  1073.             //anything you want to start after 3s
  1074.         }, 1000)
  1075.     }, 1000)
  1076. }
  1077.  
  1078.  
  1079.  
  1080. fun SendMessagePart(messages: MutableList<ChatItem>, userState: MutableState<String>, onlineStatus: MutableState<String>, sharedPreferences: SharedPreferences,  messageState: String, nextState: String, context: Context, texts: List<String>){
  1081.     onlineStatus.value = "Typing..."
  1082.     Handler().postDelayed(Runnable {
  1083.         //anything you want to start after 3s
  1084.         onlineStatus.value = "Online"
  1085.         if (userState.value == "Typing$messageState") {
  1086.             val botMess =
  1087.                 ChatItem(
  1088.                     sender = false,
  1089.                     text = texts[0]
  1090.                 )
  1091.  
  1092.             messages.add(botMess)
  1093.             vibratePhone(context = context)
  1094.  
  1095.             if (texts.size==1){
  1096.                 userState.value = nextState
  1097.                 val editor = sharedPreferences.edit()
  1098.                 editor.putString("userState", userState.value)
  1099.                 editor.apply()
  1100.                 Handler().postDelayed(Runnable {
  1101.                     //anything you want to start after 3s
  1102.                     val sdf = SimpleDateFormat("HH:mm")
  1103.                     val currentDate = sdf.format(Date())
  1104.                     if (userState.value == nextState)
  1105.                         onlineStatus.value =
  1106.                             "Was online at $currentDate"
  1107.  
  1108.                 }, 2000)
  1109.             } else{
  1110.                 SendMessagePart(messages = messages, userState, onlineStatus, sharedPreferences, messageState, nextState, context, texts=texts.slice(1..texts.size-1))
  1111.             }
  1112.         }
  1113.     }, 2000)
  1114. }
  1115.  
  1116. fun vibratePhone(context: Context) {
  1117.     val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
  1118.     if (Build.VERSION.SDK_INT >= 26) {
  1119.         vibrator.vibrate(VibrationEffect.createOneShot(50, VibrationEffect.DEFAULT_AMPLITUDE))
  1120.     } else {
  1121.         vibrator.vibrate(200)
  1122.     }
  1123. }

Editor

You can edit this paste and save as new:


File Description
  • чел
  • Paste Code
  • 24 Sep-2021
  • 54.89 Kb
You can Share it: