code

code


package com.apiscore

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.bumptech.glide.Glide
import com.google.gson.Gson
import okhttp3.*
import java.io.IOException
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.apiscore.EstatisticasActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import android.util.Log
import androidx.room.Room
import java.util.Date
import java.util.UUID
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.widget.Toast


class MainActivity : AppCompatActivity() {
    fun isOnline(): Boolean {
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val network = connectivityManager.activeNetwork ?: return false
            val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false
            return activeNetwork.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        } else {
            val networkInfo = connectivityManager.activeNetworkInfo ?: return false
            return networkInfo.isConnectedOrConnecting
        }
    }
    private var bannerImageUrl: String? = null
    private lateinit var db: AppDatabase
    private lateinit var recyclerView: RecyclerView
    private lateinit var matchAdapter: MatchAdapter
    private var offset: String? = null
    private var totalOdd = 1.0
    private val selectedOdds = mutableMapOf<String, Double>()
    private lateinit var toolbarTitle: TextView
    private lateinit var betAmount: EditText
    private lateinit var potentialWin: TextView
    private lateinit var bottomNavigationView: BottomNavigationView
    private lateinit var addBetButton: FloatingActionButton
    private lateinit var myToolbar: Toolbar
    private var currentPotentialWin: Double = 0.0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        myToolbar = findViewById(R.id.my_toolbar)
        setSupportActionBar(myToolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        myToolbar.visibility = View.INVISIBLE
        supportActionBar?.setDisplayShowTitleEnabled(false)
        bottomNavigationView = findViewById(R.id.bottom_navigation)
        toolbarTitle = findViewById(R.id.toolbar_title)
        betAmount = findViewById(R.id.bet_amount)
        potentialWin = findViewById(R.id.potential_win)
        addBetButton = findViewById(R.id.add_bet_button)
        addBetButton.visibility = View.INVISIBLE
        addBetButton.setOnClickListener { GlobalScope.launch(Dispatchers.IO) {
            val groupId = UUID.randomUUID().toString()
            val groupName = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())
            val potentialWinValue = potentialWin.text.toString().substring(3).toDoubleOrNull() ?: 0.0

            var groupStatus = "" // инициализируем статус как "won"
            val matchesForGroup = mutableListOf<Match>() // коллекция для хранения матчей группы

            selectedOdds.keys.forEach { matchId ->
                val record = matchAdapter.getRecordById(matchId)
                if (record != null) {
                    val match = Match(
                        id = record.id,
                        groupId = groupId,
                        hometeam = record.fields.hometeam,
                        awayteam = record.fields.awayteam,
                        Homeic = record.fields.Homeic,
                        awayic = record.fields.awayic,
                        result = record.fields.result,
                        matchresult = record.fields.matchresult,
                        Done = record.fields.Done,
                        odd = record.fields.odd,
                        tip = record.fields.tip,
                        data = record.fields.data,
                        time = record.fields.time,
                        tournament = record.fields.tournament
                    )
                    if (groupStatus == "") {
                        groupStatus = "won"
                    }
                    // если хотя бы один матч имеет статус "lost", то статус группы становится "lost"
                    if (record.fields.result == "lost") {
                        groupStatus = "lost"
                    } else if (record.fields.result == "pending") {
                        // если хотя бы один матч имеет статус "pending", то статус группы становится "pending",
                        // но только в том случае, если до этого не было найдено ни одного матча со статусом "lost"
                        if (groupStatus != "lost") {
                            groupStatus = "pending"
                        }

                    }

                    matchesForGroup.add(match) // добавляем матч в коллекцию матчей группы
                }
            }

            val group = Group(
                id = groupId,
                groupName = groupName,
                betAmount = betAmount.text.toString().toDouble(),
                potentialWin = currentPotentialWin,
                matchCount = selectedOdds.size,
                totalOdd = totalOdd,
                groupStatus = groupStatus  // здесь используем вычисленный статус
            )

            // сохраняем группу и матчи
            db.groupDao().insertGroup(group)
            matchesForGroup.forEach { db.matchDao().insertMatches(it) }

            selectedOdds.keys.forEach { matchId ->
                val record = matchAdapter.getRecordById(matchId)
                if (record != null) {
                    val match = Match(
                        id = record.id,
                        groupId = groupId,
                        hometeam = record.fields.hometeam,
                        awayteam = record.fields.awayteam,
                        Homeic = record.fields.Homeic,
                        awayic = record.fields.awayic,
                        result = record.fields.result,
                        matchresult = record.fields.matchresult,
                        Done = record.fields.Done,
                        odd = record.fields.odd,
                        tip = record.fields.tip,
                        data = record.fields.data,
                        time = record.fields.time,
                        tournament = record.fields.tournament
                    )
                    db.matchDao().insertMatches(match)
                }
            }
            val intent = Intent(this@MainActivity, MultActivity::class.java)
            startActivity(intent)
            val groupsWithMatches = db.groupDao().getAllGroupsWithMatches()
            groupsWithMatches.forEach { groupWithMatches ->
                Log.d("GroupWithMatches", "Group: ${groupWithMatches.group.groupName}, Bet Amount: ${groupWithMatches.group.betAmount}, Potential Win: ${groupWithMatches.group.potentialWin}, Match Count: ${groupWithMatches.group.matchCount}, Total Odd: ${totalOdd}, Group Status: ${groupWithMatches.group.groupStatus}")
                groupWithMatches.matches.forEach { match ->
                    Log.d("GroupWithMatches", match.toString())
                }
            }
        }
        }

        bottomNavigationView.selectedItemId = R.id.action_palpites
        bottomNavigationView.setOnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.action_multiplas -> {
                    val intent = Intent(this@MainActivity, MultActivity::class.java)
                    startActivity(intent)
                    true
                }

                // добавьте другие элементы нижнего меню здесь, если они есть
                else -> false
            }
        }
        betAmount.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                updatePotentialWin()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java, "AppDatabase"
        ).build()
        val swipeRefreshLayout = findViewById<SwipeRefreshLayout>(R.id.swipe_refresh_layout)
        swipeRefreshLayout.isRefreshing = true // Start loading indicator

        swipeRefreshLayout.setOnRefreshListener {
            if (isOnline()) {
                fetchMatches(true, swipeRefreshLayout)
            } else {
                Toast.makeText(this, "Sem conexão com a internet", Toast.LENGTH_SHORT).show()
                swipeRefreshLayout.isRefreshing = false
            }
        }
        recyclerView = findViewById(R.id.recycler_view)
        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager
        matchAdapter = MatchAdapter(mutableListOf())
        recyclerView.adapter = matchAdapter

        swipeRefreshLayout.setOnRefreshListener {
            fetchMatches(true, swipeRefreshLayout)
        }

        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (dy > 0) {
                    val visibleItemCount = layoutManager.childCount
                    val totalItemCount = layoutManager.itemCount
                    val pastVisibleItems = layoutManager.findFirstVisibleItemPosition()

                    if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
                        fetchMatches(false, swipeRefreshLayout)
                    }
                }
            }
        })

        if (isOnline()) {
            fetchMatches(false, swipeRefreshLayout)
        } else {
            Toast.makeText(this, "Sem conexão com a internet", Toast.LENGTH_SHORT).show()
        }
        updateTotalOdd()
        fetchBannerData() // Fetch banner data from API
    }

    private fun updatePotentialWin() {
        val betValue = betAmount.text.toString().replace("R$", "").trim().toDoubleOrNull() ?: 0.0
        val win = betValue * totalOdd
        currentPotentialWin = win.toInt().toDouble()
        potentialWin.text = "  =  R$${String.format("%.2f", win)}"
    }

    private fun updateTotalOdd() {
        val formattedTotalOdd = String.format("%.2f", totalOdd)
        toolbarTitle.text = " $formattedTotalOdd"
        updatePotentialWin()
    }

    private var isLoading = false

    private fun fetchMatches(isRefresh: Boolean, swipeRefreshLayout: SwipeRefreshLayout) {
        if (isLoading) return

        isLoading = true

        val client = OkHttpClient()
        var url =
            "https://api.airtable.com/v0/app7m37Bmsr1OpcA3/allevents?sort%5B0%5D%5Bfield%5D=Created&sort%5B0%5D%5Bdirection%5D=desc&pageSize=10"

        if (isRefresh) {
            offset = null
        } else if (!offset.isNullOrEmpty()) {
            url += "&offset=$offset"
        }

        val request = Request.Builder()
            .url(url)
            .get()
            .addHeader("Authorization", "Bearer keyF1aV2oRJe4mDUz")
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
                runOnUiThread {
                    swipeRefreshLayout.isRefreshing = false
                    isLoading = false
                }
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (!response.isSuccessful) throw IOException("Unexpected code $response")

                    val gson = Gson()
                    val matchData =
                        gson.fromJson(response.body!!.string(), MatchData::class.java)
                    offset = matchData.offset
                    runOnUiThread {
                        if (isRefresh) {
                            matchAdapter.clearMatches()
                        }
                        matchAdapter.addMatches(matchData.records)
                        swipeRefreshLayout.isRefreshing = false
                        isLoading = false
                    }
                }
            }
        })
    }

    private fun fetchBannerData() {
        val client = OkHttpClient()
        val url = "https://api.airtable.com/v0/app7m37Bmsr1OpcA3/Banner"
        val request = Request.Builder()
            .url(url)
            .get()
            .addHeader("Authorization", "Bearer keyF1aV2oRJe4mDUz")
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (!response.isSuccessful) {
                        throw IOException("Unexpected code $response")
                    }

                    val responseData = response.body?.string()
                    Log.d("API Response", responseData ?: "")

                    val gson = Gson()
                    val bannerData = gson.fromJson(responseData, BannerData::class.java)
                    if (bannerData.records.isNotEmpty()) {
                        bannerImageUrl = bannerData.records[0].fields?.Notes?.get(0)?.thumbnails?.large?.url
                        Log.d("BannerImage", "Banner Image URL: $bannerImageUrl")
                        runOnUiThread {
                            loadBannerImage()
                        }
                    }
                }
            }
        })
    }

    private fun loadBannerImage() {
        if (!bannerImageUrl.isNullOrEmpty()) {

            val bannerImageView: ImageView = findViewById(R.id.banner_image_view)
            Glide.with(bannerImageView)
                .load(bannerImageUrl)
                .into(bannerImageView)

        }
    }

    inner class MatchAdapter(private var records: MutableList<Record>) :
        RecyclerView.Adapter<MatchAdapter.MatchViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MatchViewHolder {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_match, parent, false)
            return MatchViewHolder(view)
        }

        override fun onBindViewHolder(holder: MatchViewHolder, position: Int) {
            holder.bind(records[position])
        }

        override fun getItemCount(): Int {
            return records.size
        }

        fun addMatches(newMatches: List<Record>) {
            this.records.addAll(newMatches)
            notifyDataSetChanged()
        }

        fun clearMatches() {
            this.records.clear()
            notifyDataSetChanged()
        }

        fun getRecordById(id: String): Record? {
            return this.records.find { it.id == id }
        }

        inner class MatchViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            private val homeTeamTextView: TextView = view.findViewById(R.id.home_team)
            private val awayTeamTextView: TextView = view.findViewById(R.id.away_team)
            private val tournamentTextView: TextView = view.findViewById(R.id.tournament)
            private val tipTextView: TextView = view.findViewById(R.id.tip)
            private val dataTextView: TextView = view.findViewById(R.id.data)
            private val timeTextView: TextView = view.findViewById(R.id.time)
            private val oddTextView: TextView = view.findViewById(R.id.odd)
            private val matchResultTextView: TextView = view.findViewById(R.id.match_result)
            private val homeTeamIconImageView: ImageView = view.findViewById(R.id.home_team_icon)
            private val awayTeamIconImageView: ImageView = view.findViewById(R.id.away_team_icon)
            private val resultImageView: ImageView = view.findViewById(R.id.result_image)
            private val matchSelectButton: ImageView = view.findViewById(R.id.match_select_button)

            fun bind(record: Record) {
                homeTeamTextView.text = record.fields.hometeam
                awayTeamTextView.text = record.fields.awayteam
                tournamentTextView.text = record.fields.tournament
                tipTextView.text = record.fields.tip
                dataTextView.text = record.fields.data
                timeTextView.text = record.fields.time
                matchResultTextView.text = record.fields.matchresult
                oddTextView.text = "  -  ${record.fields.odd}"

                when (record.fields.result) {
                    "won" -> resultImageView.setImageResource(R.drawable.won)
                    "lost" -> resultImageView.setImageResource(R.drawable.lost)
                    "pending" -> resultImageView.setImageResource(R.drawable.pending)
                }

                Glide.with(homeTeamIconImageView.context)
                    .load(record.fields.Homeic)
                    .into(homeTeamIconImageView)

                Glide.with(awayTeamIconImageView.context)
                    .load(record.fields.awayic)
                    .into(awayTeamIconImageView)

                matchSelectButton.setOnClickListener {
                    val matchId = record.id
                    if (selectedOdds.containsKey(matchId)) {
                        selectedOdds.remove(matchId)
                        matchSelectButton.setImageResource(R.drawable.but_def)
                        if (selectedOdds.isEmpty()) {
                            addBetButton.visibility = View.INVISIBLE
                            myToolbar.visibility = View.INVISIBLE
                        }
                    } else {
                        selectedOdds[matchId] = record.fields.odd.toDouble()
                        matchSelectButton.setImageResource(R.drawable.but_active)
                        addBetButton.visibility = View.VISIBLE
                        myToolbar.visibility = View.VISIBLE
                    }
                    totalOdd = selectedOdds.values.fold(1.0) { acc, odd -> acc * odd }
                    totalOdd = String.format("%.2f", totalOdd).toDouble()
                    updateTotalOdd()
                }

                if (selectedOdds.containsKey(record.id)) {
                    matchSelectButton.setImageResource(R.drawable.but_active)
                } else {
                    matchSelectButton.setImageResource(R.drawable.but_def)
                }
                itemView.setOnClickListener {
                    val url = "http://test.com"
                    val i = Intent(Intent.ACTION_VIEW)
                    i.data = Uri.parse(url)
                    itemView.context.startActivity(i)
                }
            }
        }
    }
}


Report Page