package de.hft.geotracker.activities

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import de.hft.geotracker.R
import de.hft.geotracker.retrofit.GeofenceService
import de.hft.geotracker.retrofit.ValuesUserLogin
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import kotlinx.android.synthetic.main.activity_login.*

/**
 * A simple [Fragment] subclass.
 */
class Login : AppCompatActivity() {
    lateinit var login: TextView
    lateinit var reg: TextView
    lateinit var service: GeofenceService

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

        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_BACKGROUND_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
                1000
            )
        } else {
            // Background location runtime permission already granted.
            // You can now call geofencingClient.addGeofences().
        }

        val retrofit = Retrofit.Builder()
            .baseUrl("http://plesk.icaotix.de:5000")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        service = retrofit.create(GeofenceService::class.java)

        login = findViewById(R.id.button_login)
        login.setOnClickListener {
            intent = Intent(this, MainActivity::class.java)
            login()
        }
        reg = findViewById(R.id.button_register)
        reg.setOnClickListener {
            register()
        }
    }

    private fun register() {
        val intent = Intent(this, Register::class.java)
        startActivity(intent)
    }

    private fun login() {
        val name = input_username.text.toString()
        val pswd = input_password.text.toString()
        val call = service.login(ValuesUserLogin(name, pswd))

        call.enqueue(object : Callback<Void> {
            override fun onResponse(call: Call<Void>?, response: Response<Void>?) {
                if (response != null && response.isSuccessful) {
                    val headers = response.headers()
                    val authentication = headers.get("Authorization")

                    deleteFile("JWToken")
                    openFileOutput("JWToken", Context.MODE_PRIVATE).use {
                        it.write(authentication!!.toByteArray())
                    }

                    println(response.code())
                    startActivity(intent)
                } else {
                    if (response != null) {
                        println(response.code())
                        Toast.makeText(this@Login, "Wrong Username or Password!", Toast.LENGTH_LONG)
                            .show()
                    } else {
                        println("Response is null")
                    }
                }
            }

            override fun onFailure(call: Call<Void>?, t: Throwable?) {
                println("Error: ${t.toString()}")
            }

        })
    }
}
