package com.example.webscraper

import android.content.Context
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.webscraper.ui.theme.WebscraperTheme
import java.io.BufferedReader
import java.io.FileInputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.Executors

class MainActivity : ComponentActivity() {

    var webthread = false
    var context: Context? = null
    var tmpdir: String? = null
    var tf: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tf = findViewById (R.id.textView)
        tf!!.movementMethod = ScrollingMovementMethod()
        val executor = Executors.newSingleThreadExecutor()
        context = this@MainActivity
        tmpdir = context!!.cacheDir.toString()
        executor.execute {
            doInBackground()
        }

        while (!webthread);
        //copying a file to the "log"
        val infile: BufferedReader =
            BufferedReader(InputStreamReader(FileInputStream("$tmpdir/tempweb.html")))
        while (true) {
            val c: Int = infile.read()
            if (c == -1) break
            tf!!.text = tf!!.text.toString() + c.toChar()
        }
        infile.close()
    }

    fun doInBackground() {
        val obj = URL("http://philos.nmu.edu/weirdal")
        val con: HttpURLConnection = obj.openConnection() as HttpURLConnection
        con.requestMethod = "GET"
        val responseCode = con.responseCode
        if (responseCode == HttpURLConnection.HTTP_OK) { //If the connection worked
            var infile = BufferedReader(InputStreamReader(con.inputStream))
            val outfile = PrintWriter("$tmpdir/tempweb.html")
            while (true) {  //copy the webpage into the temp file
                val c: Int = infile.read()
                if (c == -1) break
                outfile.print(c.toChar())
            }
            infile.close()
            outfile.close()
        } else {
            println("DID NOT WORK")
        }
        webthread = true
    }
}
