function findChatBotUiComponents(data, result = []) {
  if (!Array.isArray(data)) data = [data];
  for (const item of data) {
    if ("components" in item) {
      findChatBotUiComponents(item.components, result);
    }
    if ("children" in item) {
      findChatBotUiComponents(item.children, result);
    }
    if ("props" in item && item.name === "ChatBotUi") {
      result.push(item);
    }
  }

  return result;
}

export const buildChatBotUiImports = (fragment,configuration) => {
  if (findChatBotUiComponents(fragment).length == 0) return "";

  return `

 
  import android.graphics.Color

  import com.google.gson.Gson
  import ${configuration.packageName}.extensions.hideSoftKeyboard
  import ${configuration.packageName}.extensions.snackBar
  import ${configuration.packageName}.extensions.viewBinding
  import ${configuration.packageName}.model.remote.ChatBotRequest
  import ${configuration.packageName}.model.remote.ChatBotTextRequest
  import ${configuration.packageName}.model.remote.SingleChatMessageResponse
  import ${configuration.packageName}.model.remote.SingleChatResponse
  import ${configuration.packageName}.viewmodels.BaasViewModel
  import org.koin.android.ext.android.inject
  import org.koin.androidx.viewmodel.ext.android.viewModel
  import java.util.Date
 
     `;
};

export const getChatBotUiFields = (fragment) => {
  if (findChatBotUiComponents(fragment).length == 0) return "";

  return `
  var chatList: ArrayList<SingleChatResponse> = arrayListOf()
  var role = pref.role
    `;
};

export const generateChatBotUiFragmentBinding = (fragment) => {
  if (findChatBotUiComponents(fragment).length == 0) return "";

  return `
  val simpleChatView = binding.simpleChatView
            simpleChatView.userId = this.userId!!

            simpleChatView.setOnMessageSendListener { message ->
                //user clicked on send message button


                // val i = chatList.listIterator(chatList.size)
                // while (i.previousIndex() != chatList.size - 4) {
                //     val e = i.previous()!!
                //     print("$e ")
                // }





                var index = 0
                var messageList: ArrayList<ChatBotTextRequest> = arrayListOf()
                for (list in chatList) {

                    //if (index > 4) {
                        messageList.add(ChatBotTextRequest(list.chat?.role, list.chat?.message))
                    //}
                    index = index + 1
                }

                val messageSend = ChatBotTextRequest("user", message)
                messageList.add(messageSend)


                val sendMessage = SingleChatResponse(0, 0, 1, "", "", 0,
                    SingleChatMessageResponse(message, this.userId, false, Date().time, "user"))
                binding.simpleChatView.addMessage(sendMessage)
                chatList.add(sendMessage)

                sendTextMessageToBot(messageList)
            }
    
            simpleChatView.setOnMessageClickListener { chatMessage ->
                //user clicked on the Text Message
            }
    
            simpleChatView.setOnChatImageClickListener { chatMessage ->
                //user clicked on the image message
            }
    
            simpleChatView.setOnChatVideoClickListener { chatMessage ->
                //user clicked on the video message
            }
    
            simpleChatView.setOnChatUserImageClickListener { chatMessage ->
                //user clicked on the profile pic
            }
    
            simpleChatView.setOnChatUsernameClickListener { chatMessage ->
                //user clicked on the username
            }

    
    
            simpleChatView.setChatViewBackground(Color.WHITE)
            simpleChatView.setSendButtonColor(Color.BLUE)
            simpleChatView.setAddButtonColor(Color.RED)
            simpleChatView.setChatInputBackgroundColor(Color.LTGRAY)
            simpleChatView.setChatInputBackground(R.drawable.chat_input_shape)
            simpleChatView.setShowAddButton(false)
            simpleChatView.setShowSenderLayout(true or false)
            simpleChatView.setShowImageButton(false)
            simpleChatView.setShowVideoButton(false)
            simpleChatView.setShowCameraButton(false)
            simpleChatView.setHint("Type message...")
            simpleChatView.setHintTextColor(Color.parseColor("#929292"))
            simpleChatView.setTextColor(Color.BLACK)

            val response = pref.chatBotResponse
            if (response?.isEmpty() != true) {
                val list =
                    Gson().fromJson(pref.chatBotResponse, Array<SingleChatResponse>::class.java)
                chatList.addAll(list)

                for (message in chatList) {
                    binding.simpleChatView.addMessage(message)
                }
            }
    `;
};

export const generateChatBotUiFunction = (fragment, configuration) => {
  if (findChatBotUiComponents(fragment).length == 0) return "";

  return `
  override fun onPause() {
    super.onPause()

    val chatResponse = Gson().toJson(chatList)
    pref.saveChatBotResponse(chatResponse)
}


fun sendTextMessageToBot(messageList: ArrayList<ChatBotTextRequest>) {

    val gsonLIST = Gson().toJson(messageList)
    requireActivity().hideSoftKeyboard()
    baasViewModel.sendMessageToBot(ChatBotRequest(messageList)).observe(viewLifecycleOwner) {
        when (it.status) {
            Status.ERROR -> snackBar(it.message ?: getString(R.string.something_went_wrong))
            Status.LOADING -> {
                snackBar("receving message...")
            }

            Status.SUCCESS -> {


                val lst = it.data?.message

                if (lst != null) {


                    for (message in lst) {
                        val content = message.message?.content
                        val receivedMessage = SingleChatResponse(0, 0, 1, "", "", 0,
                            SingleChatMessageResponse(content, 0, false, Date().time, message.message?.role))
                        binding.simpleChatView.addMessage(receivedMessage)

                        chatList.add(receivedMessage)
                    }
                }
            }
        }
    }
}

    `;
};
