package com.example.sonya

import android.Manifest
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.Color
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioRecord
import android.media.AudioTrack
import android.media.MediaRecorder
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import java.io.InputStream
import java.io.OutputStream
import java.net.ServerSocket
import java.net.Socket
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    private val sampleRate = 44100
    private var isRecording = false
    private lateinit var recordButton: Button
    private var animator: ObjectAnimator? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recordButton = findViewById(R.id.recordButton)

        // Запрос разрешений
        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.INTERNET), 1)

        recordButton.setOnClickListener {
            if (isRecording) {
                stopRecording()
            } else {
                startRecording()
            }
        }

        startAudioPlayback()
        startSocketServer()
    }

    private fun startSocketServer() {
        thread {
            try {
                val serverSocket = ServerSocket(51411)
                while (true) {
                    val clientSocket: Socket = serverSocket.accept()
                    val inputStream: InputStream = clientSocket.getInputStream()
                    val buffer = ByteArray(1024)
                    val read = inputStream.read(buffer)
                    val message = String(buffer, 0, read)

                    when (message) {
                        "ACTIVATED" -> {
                            runOnUiThread {
                                onActivationReceived()
                            }
                        }
                        "DEACTIVATED" -> {
                            runOnUiThread {
                                onDeactivationReceived()
                            }
                        }
                    }

                    inputStream.close()
                    clientSocket.close()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun onActivationReceived() {
        recordButton.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#FFCC0000"))
    }

    private fun onDeactivationReceived() {
        recordButton.backgroundTintList = null
    }

    private fun startAudioPlayback() {
        thread {
            try {
                val socket = ServerSocket(51412) // Новый порт для приема аудио
                val clientSocket: Socket = socket.accept()
                val inputStream: InputStream = clientSocket.getInputStream()

                // Получаем аудиоформат
                val bufferSize = AudioTrack.getMinBufferSize(
                    48000,
                    AudioFormat.CHANNEL_OUT_MONO,
                    AudioFormat.ENCODING_PCM_16BIT
                )
                val audioTrack = AudioTrack(
                    AudioManager.STREAM_MUSIC,
                    48000,
                    AudioFormat.CHANNEL_OUT_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    bufferSize,
                    AudioTrack.MODE_STREAM
                )
                audioTrack.play()

                val buffer = ByteArray(bufferSize)
                var read: Int

                while (inputStream.read(buffer).also { read = it } != -1) {
                    audioTrack.write(buffer, 0, read)
                }

                audioTrack.stop()
                audioTrack.release()
                inputStream.close()
                clientSocket.close()
                socket.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    @SuppressLint("MissingPermission")
    private fun startRecording() {
        isRecording = true
        animateButton(true) // Начинаем анимацию

        Thread {
            val bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
            val audioRecord = AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize)
            audioRecord.startRecording()

            try {
                val socket = Socket("192.168.0.105", 6543)
                val outputStream: OutputStream = socket.getOutputStream()
                val buffer = ByteArray(bufferSize)

                while (isRecording) {
                    val read = audioRecord.read(buffer, 0, buffer.size)
                    outputStream.write(buffer, 0, read)
                }

                outputStream.close()
                socket.close()
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                audioRecord.stop()
                audioRecord.release()
            }
        }.start()
    }

    private fun stopRecording() {
        isRecording = false
        animateButton(false) // Останавливаем анимацию
    }

    private fun animateButton(isRecording: Boolean) {
        if (isRecording) {
            // Запускаем анимацию
            animator = ObjectAnimator.ofFloat(recordButton, "scaleX", 1.0f, 1.2f)
            animator?.duration = 300
            animator?.repeatCount = ObjectAnimator.INFINITE
            animator?.repeatMode = ObjectAnimator.REVERSE
            animator?.start()
        } else {
            // Останавливаем анимацию
            animator?.cancel()
            recordButton.scaleX = 1.0f // Возвращаем к исходному размеру
        }
    }
}

У меня проблема, похоже что пока воспроизводится полученное аудио в другом потоке продолжается прослушивание с микрофона, что накладывается друг на друга и не корректно работает, как это исправить?