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 var isPlayingAudio = false
    private lateinit var recordButton: Button
    private var animator: ObjectAnimator? = null
    private var audioServerSocket: ServerSocket? = 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() {
        if (audioServerSocket == null) {
            thread {
                try {
                    audioServerSocket = ServerSocket(51412) // Создаем серверный сокет один раз
                    while (true) {
                        val clientSocket: Socket = audioServerSocket!!.accept()
                        handleAudioClient(clientSocket)
                    }
                } catch (e: Exception) {
                    e.printStackTrace() // Логируем ошибку
                }
            }
        }
    }

    private fun handleAudioClient(clientSocket: Socket) {
        var inputStream: InputStream? = null
        try {
            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()
            isPlayingAudio = true // Устанавливаем флаг воспроизведения

            val buffer = ByteArray(bufferSize)
            var read: Int

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

            audioTrack.stop()
            audioTrack.release()
        } catch (e: Exception) {
            e.printStackTrace() // Логируем ошибку
        } finally {
            try {
                inputStream?.close()
                clientSocket.close()
            } catch (e: Exception) {
                e.printStackTrace() // Логируем ошибку при закрытии
            }
            isPlayingAudio = false // Сбрасываем флаг воспроизведения
        }
    }

    @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) {
                    // Приостанавливаем запись, если идет воспроизведение аудио
                    if (isPlayingAudio) {
                        Thread.sleep(1000) // Ждем, прежде чем проверить снова
                        continue
                    }

                    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 // Возвращаем к исходному размеру
        }
    }
}

Мне надо чтобы запись и передача записи по сокету происходило даже если приложение свернуто или потушен экран