package com.example.randomtaskmobile

import GlobalSharedPreferences
import TaskStorage
import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.AlertDialog
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationManagerCompat
import api.RetrofitConnection
import com.example.randomtaskmobile.databinding.ActivityGenerateTaskBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import model.AppDatabase
import model.BoredTask
import model.TaskEntity
import model.Translate
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.time.LocalDateTime
import java.util.Calendar
import java.util.Date


class GenerateTaskActivity : AppCompatActivity() {
    private lateinit var shPref: GlobalSharedPreferences
    private lateinit var binding: ActivityGenerateTaskBinding
    private var randomTask: TaskEntity? = null
    private lateinit var work : String

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityGenerateTaskBinding.inflate(layoutInflater)
        setContentView(binding.root)

        Log.d("Notif", "Create")
        createNotificationChannel()

        shPref = GlobalSharedPreferences(this)
        work = intent.getStringExtra("work")!!
        if(work == "create"){
            generateTask()
        }
        else if(work == "update"){
            randomTask = AppDatabase.getInstance(applicationContext).taskDao().getTask(intent.getIntExtra("idTask", 0))
            with(binding){
                resetButton.visibility = View.GONE
                titleTask.text = randomTask!!.name.toString()
                if(randomTask!!.description != null)
                    descriptionActivity.setText(randomTask!!.description)
                if(randomTask!!.dateTimeTo!=null){
                    addReminderCheckbox.isChecked = true
                    addReminderLayout.visibility = View.VISIBLE
                    var date = randomTask!!.dateTimeTo!!
                    dateActivity.updateDate(date.year, date.monthValue, date.dayOfMonth)
                    timeActivity.hour = date.hour
                    timeActivity.minute = date.minute
                }
            }
        }
        listener()


    }


    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel()
    {
        val name = "Notif Channel"
        val desc = "A Description of the Channel"
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel(channelID, name, importance)
        channel.description = desc
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
        Log.d("Notif", "Finish create")
    }


    private fun scheduleNotification(){
        val intent = Intent(applicationContext, Notification::class.java)
        val title = binding.titleTask.text.toString()
        val message = binding.descriptionActivity.text.toString()
        intent.putExtra(titleExtra, title)
        intent.putExtra(messageExtra, message)

        val pendingIntent = PendingIntent.getBroadcast(
            applicationContext,
            notificationID,
            intent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )

        val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val time = getTime()
        Log.d("Alarm", "BeforeAlarm schedule Notification")

        alarmManager.setExactAndAllowWhileIdle(
            AlarmManager.RTC_WAKEUP,
            time,
            pendingIntent
        )
//        alarmManager.setAlarmClock(
//            AlarmManager.AlarmClockInfo(time, pendingIntent),
//            pendingIntent
//        )
        Log.d("Alarm", "After Alarm schedule Notification")

        //showAlert(time, title, message)
    }

    private fun showAlert(time: Long, title: String, message: String) {
        val date = Date(time)
        val dateFormat = android.text.format.DateFormat.getLongDateFormat(applicationContext)
        val timeFormat = android.text.format.DateFormat.getTimeFormat(applicationContext)

        AlertDialog.Builder(this)
            .setTitle("Random Task")
            .setMessage(title + "\n" + message + "\n" + "\n\t"+dateFormat.format(date)+" "+timeFormat.format(date))
            .setPositiveButton("Ок"){_,_->}
            .show()

    }

    private fun getTime(): Long {
        val minute = binding.timeActivity.minute
        val hour = binding.timeActivity.hour
        val day = binding.dateActivity.dayOfMonth
        val month = binding.dateActivity.month
        val year = binding.dateActivity.year

        val calendar = Calendar.getInstance()
        calendar.set(year, month, day, hour, minute, 0)
        return calendar.timeInMillis
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun checkNotificationPermissions(context: Context): Boolean {
        // Check if notification permissions are granted
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            val isEnabled = notificationManager.areNotificationsEnabled()

            if (!isEnabled) {
                // Open the app notification settings if notifications are not enabled
                val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
                context.startActivity(intent)

                return false
            }
        } else {
            val areEnabled = NotificationManagerCompat.from(context).areNotificationsEnabled()

            if (!areEnabled) {
                // Open the app notification settings if notifications are not enabled
                val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
                context.startActivity(intent)

                return false
            }
        }

        // Permissions are granted
        return true
    }


    //Генерация случайной задачи. Обращение к АПИ
    private fun generateTask()
    {
        //получение активности
        CoroutineScope(Dispatchers.IO).launch {
            binding.showProgressGenerate.visibility = View.VISIBLE
            binding.aboutTaskLayout.visibility = View.GONE
            getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            val responseActivity = RetrofitConnection.getRerofit("http://www.boredapi.com/").GetTask()
                .enqueue(object : Callback<BoredTask> {
                    override fun onResponse(call: Call<BoredTask>, response: Response<BoredTask>) {
                        if (response.isSuccessful) {
                            val task = response.body()!!
                            Log.d("ResponseGetTask", task.toString())

                            //перевод
                            CoroutineScope(Dispatchers.IO).launch {
                                val responseTranslate = RetrofitConnection.getRerofit("https://ftapi.pythonanywhere.com/")
                                    .GetTranslate("ru", task.activity).enqueue(object : Callback<Translate>{
                                        override fun onResponse(
                                            call: Call<Translate>,
                                            response: Response<Translate>
                                        ) {
                                            if(response.isSuccessful)
                                            {
                                                val translatedTask = response.body()!!
                                                Log.d("ResponseTranslateTask", translatedTask.toString())

                                                randomTask = TaskEntity(0, translatedTask.destination_text, null, null, false)
                                                with(binding)
                                                {
                                                    showProgressGenerate.visibility = View.GONE
                                                    aboutTaskLayout.visibility = View.VISIBLE
                                                    titleTask.text = randomTask!!.name.toString()
                                                }
                                                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                                            }
                                            else{
                                                Log.d("ResponseTranslateTaskError", response.errorBody().toString())
                                            }
                                        }

                                        override fun onFailure(call: Call<Translate>, t: Throwable) {
                                            Log.d("ResponseTranslateTask", t.toString())
                                            Toast.makeText(this@GenerateTaskActivity,"Проверьте подключение к интернету и перезапустите приложение!", Toast.LENGTH_LONG).show()
                                            error(t.toString())
                                        }
                                    })
                            }

                        } else {
                            Log.d("ResponseGetTaskError", response.errorBody().toString())
                        }
                    }

                    override fun onFailure(call: Call<BoredTask>, t: Throwable) {
                        Log.d("ResponseGetTask", t.toString())
                        Toast.makeText(this@GenerateTaskActivity,"Проверьте подключение к интернету и перезапустите приложение!", Toast.LENGTH_LONG).show()
                        error(t.toString())
                    }
                })}
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun listener()
    {
        with(binding)
        {
            resetButton.setOnClickListener()
            {
                var intent = Intent(this@GenerateTaskActivity, GenerateTaskActivity::class.java)
                intent.putExtra("work", work)
                startActivity(intent)
                finish()
            }

            backButton.setOnClickListener(){
                if(!shPref.firstStartApp)
                {
                    startActivity(Intent(this@GenerateTaskActivity, ListTaskActivity::class.java))
                }
                finish()
            }

            addReminderCheckbox.setOnCheckedChangeListener{ _, isChecked ->
                if (isChecked){
                    addReminderLayout.visibility = View.VISIBLE
                }else{
                    addReminderLayout.visibility = View.GONE
                }
            }

            saveActivity.setOnClickListener()
            {
                var db = AppDatabase.getInstance(applicationContext)

                if (work == "create"){
                    randomTask = TaskEntity(0, titleTask.text.toString(), null, null, false)
                    if(!descriptionActivity.text.isNullOrEmpty()){
                        randomTask!!.description = descriptionActivity.text.toString()
                    }
                    if(addReminderCheckbox.isChecked){
                        //var str = DateTimeFormatter.ofPattern("yyyy-MM-ddThh:mm:ss")
                        var strDate = "${String.format("%04d", dateActivity.year)}-${String.format("%02d", dateActivity.month)}-" +
                                "${String.format("%02d", dateActivity.dayOfMonth)}T${String.format("%02d",timeActivity.hour)}:${String.format("%02d",timeActivity.minute)}:00"
                        randomTask!!.dateTimeTo = LocalDateTime.parse(strDate)
                        if (checkNotificationPermissions(this@GenerateTaskActivity)) {
                            // Schedule a notification
                            scheduleNotification()
                        }
                    }
                    db.taskDao().insertAll(randomTask!!)
                }
                else if(work == "update"){
                    if(randomTask!!.description.isNullOrEmpty()){
                        randomTask!!.description = descriptionActivity.text.toString()
                    }
                    else randomTask!!.description = null
                    if(addReminderCheckbox.isChecked){
                        var strDate = "${String.format("%04d", dateActivity.year)}-${String.format("%02d", dateActivity.month)}-" +
                                "${String.format("%02d", dateActivity.dayOfMonth)}T${String.format("%02d",timeActivity.hour)}:${String.format("%02d",timeActivity.minute)}:00"
                        randomTask!!.dateTimeTo = LocalDateTime.parse(strDate)
                        if (checkNotificationPermissions(this@GenerateTaskActivity)) {
                            // Schedule a notification
                            scheduleNotification()
                        }
                    }
                    else {
                        randomTask!!.dateTimeTo = null
                    }
                    db.taskDao().updateTasks(randomTask!!)
                }
                //TaskStorage.listItem = AppDatabase.getInstance(this@GenerateTaskActivity).taskDao().getAllNotComplete()
                startActivity(Intent(this@GenerateTaskActivity, ListTaskActivity::class.java))
                finish()
            }
        }
    }
}