package com.example.divisores

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

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

        val bCalDiv = findViewById<Button>(R.id.bCalDiv)
        // set on-click listener
        bCalDiv.setOnClickListener {
            Toast.makeText(
                this@MainActivity, "Obteniendo los divisores...",
                Toast.LENGTH_SHORT).show()
            try {
                val divisores: MutableList<Int> = mutableListOf()
                val factores: MutableList<Int> = mutableListOf()
                var n: Int = Math.abs(eTNumero.text.toString().toInt())
                val n0: Int = n

                for (x in 1..n + 1) {
                    if (n % x == 0) {
                        divisores.add(x)
                    }
                }

                while (n > 1) {
                    for (x in 2..n + 1) {
                        if (n % x == 0) {
                            factores.add(x)
                            n /= x
                            break
                        }
                        if (n == 1) {
                            break
                        }
                    }
                }
                factores.reverse()
                var cadf: String = ""
                for (f in factores) {
                    cadf = "$cadf$f·"
                }
                cadf += "1"
                var primo: String = " "
                if (factores.size == 1) {
                    primo = "El número $n0 es primo"
                }
                val tamD: Int = divisores.size
                val salida: String = """
                 Divisores de $n0: $divisores
                 
                 Son $tamD divisores 
                 
                 Factores de $n0: $cadf
                 
                 $primo
            """
                tVSalida.text = salida
            } catch (e: Exception) {
                Toast.makeText(this@MainActivity, "Error ${e.message}",
                    Toast.LENGTH_LONG).show()

            }
        }
    }
}