/**
 * ProjectLaogai
 *
 * Copyright 2019-2020  <seil0@mosad.xyz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */

package org.mosad.seil0.projectlaogai

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.text.HtmlCompat
import androidx.viewpager.widget.ViewPager
import kotlinx.coroutines.*
import org.mosad.seil0.projectlaogai.controller.cache.CacheController
import org.mosad.seil0.projectlaogai.controller.preferences.EncryptedPreferences
import org.mosad.seil0.projectlaogai.controller.preferences.Preferences
import org.mosad.seil0.projectlaogai.databinding.ActivityOnboardingBinding
import org.mosad.seil0.projectlaogai.onboarding.ViewPagerAdapter
import org.mosad.seil0.projectlaogai.uicomponents.dialogs.CourseSelectionDialog
import org.mosad.seil0.projectlaogai.uicomponents.dialogs.LoadingDialog

class OnboardingActivity : AppCompatActivity() {

    private lateinit var binding: ActivityOnboardingBinding
    companion object {
        val layouts = intArrayOf(R.layout.fragment_on_welcome, R.layout.fragment_on_course, R.layout.fragment_on_login)
    }
    private lateinit var viewPager: ViewPager
    private lateinit var viewPagerAdapter: ViewPagerAdapter
    private lateinit var linLayoutDots: LinearLayout
    private lateinit var dots: Array<TextView>

    private lateinit var editTextEmail: EditText
    private lateinit var editTextPassword: EditText


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityOnboardingBinding.inflate(layoutInflater)
        setContentView(binding.root)

        viewPager = findViewById(R.id.viewPager)
        linLayoutDots = findViewById(R.id.linLayout_Dots)

        addBottomDots(0)

        viewPagerAdapter = ViewPagerAdapter(this)
        viewPager.adapter = viewPagerAdapter
        viewPager.addOnPageChangeListener(viewPagerPageChangeListener)

        // we don't use the skip button, instead we use the start button to skip the last fragment
        binding.btnSkip.visibility = View.GONE
    }

    fun btnNextClick(@Suppress("UNUSED_PARAMETER")v: View) {
        if (viewPager.currentItem < layouts.size - 1) {
            viewPager.currentItem++
        } else {
            launchHomeScreen()
        }
    }

    fun btnSkipClick(@Suppress("UNUSED_PARAMETER")v: View) {
        launchHomeScreen()
    }

    fun btnSelectCourseClick(v: View) {
        CourseSelectionDialog(this).show {
            list = CacheController.coursesList.map { it.courseName }
            listItems {
                val loadingDialog = LoadingDialog(context)
                loadingDialog.show()

                GlobalScope.launch(Dispatchers.Default) {
                    Preferences.saveCourse(context, CacheController.coursesList[selectedIndex]) // save the course

                    // update current & next weeks timetable
                    val threads = listOf(
                        CacheController.updateTimetable(Preferences.course.courseName, 0, context),
                        CacheController.updateTimetable(Preferences.course.courseName, 1, context)
                    )
                    threads.joinAll() // blocking since we want the new data

                    withContext(Dispatchers.Main) {
                        loadingDialog.dismiss()
                    }
                }
            }
            onDismiss {
                btnNextClick(v) // show the next fragment
            }
        }
    }

    fun btnLoginClick(@Suppress("UNUSED_PARAMETER")v: View) {
        editTextEmail = findViewById(R.id.editText_email)
        editTextPassword = findViewById(R.id.editText_password)

        // get login credentials from gui
        val email = editTextEmail.text.toString()
        val password = editTextPassword.text.toString()

        // save the credentials
        EncryptedPreferences.saveCredentials(email, password, this)

        launchHomeScreen()
    }

    private fun addBottomDots(currentPage: Int) {
        dots = Array(layouts.size) { TextView(this) }
        linLayoutDots.removeAllViews()

        dots.forEach {
            it.text = HtmlCompat.fromHtml("&#8226;", HtmlCompat.FROM_HTML_MODE_LEGACY)
            it.textSize = 35f
            it.setTextColor(Color.parseColor("#cccccc"))
            linLayoutDots.addView(it)
        }

        if (dots.isNotEmpty())
            dots[currentPage].setTextColor(Color.parseColor("#000000"))
    }

    private fun launchHomeScreen() {
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }

    private var viewPagerPageChangeListener: ViewPager.OnPageChangeListener = object : ViewPager.OnPageChangeListener {

        override fun onPageSelected(position: Int) {
            addBottomDots(position)
            // changing the next button text to skip for the login fragment
            if (position == layouts.size - 1) {
                binding.btnNext.text = getString(R.string.skip)
                binding.btnNext.visibility = View.VISIBLE
                binding.btnSkip.visibility = View.GONE
            } else {
                binding.btnNext.visibility = View.GONE
                binding.btnSkip.visibility = View.GONE
            }
        }

        override fun onPageScrolled(arg0: Int, arg1: Float, arg2: Int) {}
        override fun onPageScrollStateChanged(arg0: Int) {}
    }

}