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

  return result;
}

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

  return `
 
//   import ${configuration.name}.databinding.FragmentChatUiBinding
  import ${configuration.name}.databinding.FragmentHomeBinding
  import android.app.Activity
  import android.content.Intent
  import android.graphics.Bitmap
  import android.graphics.Color
  import android.net.Uri
  import android.os.Handler
  import android.os.Looper
  import android.os.Message
  import android.provider.MediaStore
  import android.widget.Toast
  import android.widget.VideoView
  import androidx.activity.result.ActivityResultCallback
  import androidx.activity.result.ActivityResultLauncher
  import androidx.activity.result.contract.ActivityResultContracts
  import androidx.navigation.fragment.findNavController
  import ${configuration.packageName}.extensions.RequestCodes
  import ${configuration.packageName}.extensions.hideSoftKeyboard
  import ${configuration.packageName}.extensions.loadImageFromUrl
  import ${configuration.packageName}.extensions.snackBar
  import ${configuration.packageName}.extensions.viewBinding
  import ${configuration.packageName}.model.remote.ChatMessage
  import ${configuration.packageName}.model.remote.SingleChatMessageResponse
  import ${configuration.packageName}.model.remote.SingleChatResponse
  import ${configuration.packageName}.utils.FileUtils.saveImage
  import ${configuration.packageName}.viewmodels.BaasViewModel
  import ${configuration.packageName}.widget.SimpleChatView
  import kotlinx.coroutines.CoroutineScope
  import kotlinx.coroutines.Dispatchers
  import kotlinx.coroutines.launch
  import okhttp3.MediaType.Companion.toMediaTypeOrNull
  import okhttp3.MultipartBody
  import okhttp3.RequestBody.Companion.asRequestBody
  import org.jetbrains.annotations.Nullable
  import org.koin.android.ext.android.inject
  import org.koin.androidx.viewmodel.ext.android.viewModel
  import java.io.File
  import java.io.IOException
  import java.util.Date
  import java.util.UUID




 
     `;
};

export const getChatUiFields = (fragment) => {
  if (findComponents(fragment ).length == 0) return "";

  return `

        private var chatMessageList:ArrayList<SingleChatResponse> = arrayListOf()
        private val position = 0
          lateinit var room_id:String
          lateinit var mainHandler: Handler
    `;
};

export const generateChatUiFragmentBinding = (fragment) => {
  if (findComponents(fragment ).length == 0) return "";

  return `
  mainHandler = Handler(Looper.getMainLooper())

  room_id = arguments?.getString("roomid").toString()

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

/*  //sending text message
  simpleChatView.addMessage(
      ChatMessage(
          UUID.randomUUID().toString(),//message id
          "Hello world",//message
          "John Doe",//username
          "http://www.maxspring.ch/images/cartoons/4.jpg",//profile url
          false,//for setting left or right position of the chat
          System.currentTimeMillis(),//timestamp
          SimpleChatView.TYPE_TEXT//message type
      )
  )

  //sending image message
  simpleChatView.addMessage(
      ChatMessage(
          UUID.randomUUID().toString(),//message id
          "http://www.maxspring.ch/images/cartoons/c71.png",//image url
          "John Doe",//username
          "http://www.maxspring.ch/images/cartoons/4.jpg",//profile url
          true,//for setting left or right position of the chat
          System.currentTimeMillis(),//timestamp
          SimpleChatView.TYPE_IMAGE//message type
      )
  )

  //sending video message
  simpleChatView.addMessage(
      ChatMessage(
          UUID.randomUUID().toString(),//message id
          "http://www.maxspring.ch/images/cartoons/Kultursponsoring.jpg",//video url
          "John Doe",//username
          "http://www.maxspring.ch/images/cartoons/4.jpg",//profile url
          true,//for setting left or right position of the chat
          System.currentTimeMillis(),//timestamp
          SimpleChatView.TYPE_VIDEO//message type
      )
  )*/


  //adding list of messages
  //simpleChatView.addMessage(chatMessageList)


  //removing message
  //simpleChatView.remove(position)

  //simpleChatView.remove(ChatMessage())

  //simpleChatView.clearMessages()//clears all the added messages


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

      sendTextMessage(room_id, message)

      /*simpleChatView.addMessage(
          ChatMessage(
              UUID.randomUUID().toString(),//message id
              message,//message
              "John Doe",//username
              "http://www.maxspring.ch/images/cartoons/4.jpg",//profile url
              true,//for setting left or right position of the chat
              System.currentTimeMillis(),//timestamp
              SimpleChatView.TYPE_TEXT//message type
          )
      )*/
  }

  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.setOnSelectImageClickListener {
      //user clicked on the image selection button

      /*val chatMessage = SingleChatResponse(0, room_id.toInt(), 1, "", "", 0,
          SingleChatMessageResponse("http://www.maxspring.ch/images/cartoons/c71.png", this.userId, true, Date().time))

      binding.simpleChatView.addMessage(chatMessage)*/

      val intent = Intent().apply {
          type = "image/*"
          action = Intent.ACTION_GET_CONTENT
      }
      startActivityForResult(
          Intent.createChooser(intent, "Select image"), RequestCodes.GALLERY_IMAGE
      )
  }

  simpleChatView.setOnSelectVideoClickListener {
      //user clicked on the video selection button
  }

  simpleChatView.setOnSelectCameraClickListener {
      //user clicked on the camera button

      /*val chatMessage = SingleChatResponse(0, room_id.toInt(), 1, "", "", 0,
          SingleChatMessageResponse("http://www.maxspring.ch/images/cartoons/c71.png", this.userId, true, Date().time))

      binding.simpleChatView.addMessage(chatMessage)*/

      startActivityForResult(
          Intent(MediaStore.ACTION_IMAGE_CAPTURE), RequestCodes.CAMERA_IMAGE
      )
  }


  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(true or false)
  simpleChatView.setShowSenderLayout(true or false)
  simpleChatView.setShowImageButton(true or false)
  simpleChatView.setShowVideoButton(false)
  simpleChatView.setShowCameraButton(true or false)
  simpleChatView.setHint("Type message...")
  simpleChatView.setHintTextColor(Color.parseColor("#929292"))
  simpleChatView.setTextColor(Color.BLACK)

  getAllChats(room_id)

  startPooling()
    `;
};

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

  return `
  override fun onPause() {
    super.onPause()
    mainHandler.removeCallbacks(updateTextTask)
}

override fun onResume() {
    super.onResume()
    mainHandler.post(updateTextTask)
}

private val updateTextTask = object : Runnable {
    override fun run() {
        minusOneSecond()
        mainHandler.postDelayed(this, 5000)
    }
}

fun minusOneSecond() {
    //getAllChats(room_id)
}

private fun uploadProfileImage(image: Bitmap) {
    val file = File(saveImage(image))
    val contentType = "multipart/form-data".toMediaTypeOrNull()
    val part = MultipartBody.Part.createFormData(
        "file", file.name, file.asRequestBody(contentType)
    )
    baasViewModel.uploadimages3( part ).observe(viewLifecycleOwner) {
        when (it.status) {
            Status.ERROR -> {
                snackBar(it.message ?: "Something went wrong")
            }
            Status.LOADING -> {
                snackBar("sending message...")
            }
            Status.SUCCESS -> {
                //pref.photo = it.data?.url
                //binding.ivUser.loadImageFromUrl(pref.photo)

                val chatMessage = SingleChatResponse(0, room_id.toInt(), 1, "", "", 0,
                    SingleChatMessageResponse(it.data?.url, this.userId, true, Date().time))

                binding.simpleChatView.addMessage(chatMessage)
            }
        }
    }
}


fun sendTextMessage(room_id: String, message: String) {

    requireActivity().hideSoftKeyboard()
    baasViewModel.sendTextMessage(room_id, this.userId!!, message).observe(viewLifecycleOwner) {
        when (it.status) {
            Status.ERROR -> snackBar(it.message ?: getString(R.string.something_went_wrong))
            Status.LOADING -> {
                snackBar("sending message...")
            }

            Status.SUCCESS -> {
                //getAllChats(room_id)

                val chatMessage = SingleChatResponse(0, room_id.toInt(), 1, "", "", 0,
                    SingleChatMessageResponse(message, this.userId, false, Date().time))
                //chatMessageList.add(chatMessage)

                binding.simpleChatView.addMessage(chatMessage)
            }
        }
    }
}

fun getAllChats(room_id: String) {

  requireActivity().hideSoftKeyboard()
  baasViewModel.getChats(room_id).observe(viewLifecycleOwner) {
      when (it.status) {
          Status.ERROR -> snackBar(it.message ?: getString(R.string.something_went_wrong))
          Status.LOADING -> {
              //snackBar("loading list...")
          }

          Status.SUCCESS -> {
              val chatList = it.data?.model
              if (chatList != null) {
                  chatMessageList.clear()
                  chatMessageList.addAll(chatList)

                  val simpleChatView = binding.simpleChatView
                  simpleChatView.setUserID(this.userId!!)
                  simpleChatView.addMessage(chatMessageList)
              }
          }
      }
  }
}

fun startPooling() {

    requireActivity().hideSoftKeyboard()
    baasViewModel.getStartPool(this.userId!!).observe(viewLifecycleOwner) {
        when (it.status) {
            Status.ERROR ->  {

                startPooling()
                snackBar(it.message ?: getString(R.string.something_went_wrong))
            }
            Status.LOADING -> {
                //snackBar("loading list...")

            }

            Status.SUCCESS -> {
                it.data?.timestamp = Date().time
                val chatMessage = SingleChatResponse(0, room_id.toInt(), 1, "", "", 0, it.data)
                //chatMessageList.add(chatMessage)
                binding.simpleChatView.addMessage(chatMessage)
                startPooling()
            }
        }
    }
}

@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (data != null) {
        if (requestCode == RequestCodes.GALLERY_IMAGE) {
            val contentURI: Uri? = data.data
            try {
                val bitmap =
                    MediaStore.Images.Media.getBitmap(activity?.contentResolver, contentURI)
                uploadProfileImage(bitmap)
            } catch (e: IOException) {
                e.printStackTrace()
                Toast.makeText(context, "Failed!", Toast.LENGTH_SHORT).show()
            }
        }
        if (requestCode == RequestCodes.CAMERA_IMAGE) {
            try {
                val bitmap = data.extras?.get("data") as Bitmap
                uploadProfileImage(bitmap)
            } catch (e: IOException) {
                e.printStackTrace()
                Toast.makeText(context, "Failed!", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
    `;
};
