package com.jkanetwork.st.frasesdeanime

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import org.jetbrains.anko.*
import android.util.Log
import android.content.Context
import android.content.SharedPreferences
import android.view.Menu
import android.view.View
import android.view.MenuItem
import java.util.Calendar
import java.text.DateFormatSymbols
import androidx.viewpager.widget.ViewPager
import android.widget.Toast

import kotlinx.android.synthetic.main.activity_main.*

/* Ads */
import com.google.android.gms.ads.AdRequest
import com.google.ads.mediation.admob.AdMobAdapter
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.reward.RewardItem
import com.google.android.gms.ads.reward.RewardedVideoAd
import com.google.android.gms.ads.reward.RewardedVideoAdListener

import com.google.android.gms.ads.AdView
import android.text.method.ScrollingMovementMethod


class MainActivity : AppCompatActivity(), RewardedVideoAdListener  {

    // Overrides for making it compile ok, it needs all methods
    override fun onRewardedVideoAdLeftApplication() {}
    override fun onRewardedVideoAdClosed() {}
    override fun onRewardedVideoAdFailedToLoad(errorCode: Int) {}
    override fun onRewardedVideoAdLoaded() {}
    override fun onRewardedVideoAdOpened() {}
    override fun onRewardedVideoStarted() {}
    override fun onRewardedVideoCompleted() {}

    /* Prefs, database init and calendar data */
    lateinit var P: Prefs
    lateinit var db: SQLiteHelper
    var cal = Calendar.getInstance()
    var dayS = cal.get(Calendar.DAY_OF_MONTH)
    var monthS = cal.get(Calendar.MONTH)+1
    var yearS = cal.get(Calendar.YEAR)

    var IDFraseS = -2 /* Error if not changes */

    lateinit var mRewardedVideoAd: RewardedVideoAd
    lateinit var mAdView : AdView


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

        P = Prefs(applicationContext)
        db = SQLiteHelper(applicationContext)


        /* Ads */
        // Initialize the Mobile Ads SDK.
        MobileAds.initialize(this, this.getString(R.string.admob_id))

        mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this)
        mRewardedVideoAd.setRewardedVideoAdListener(this);

        val extras = Bundle()

        extras.putString("max_ad_content_rating", "PG") //Non adult ads

        mAdView = adView
        val adRequest = AdRequest.Builder().addNetworkExtrasBundle(AdMobAdapter::class.java, extras).build()
        mAdView.loadAd(adRequest)

        /* Check if first time or not, for welcoming user */
        if (P.getFirstTime() == true){
            alert("Bienvenido a Frases de anime! Un lugar donde puedes descubrir las frases de tus animes favoritos, todos los días!\n" +
                    "Selecciona de la siguiente lista los que más te gusten para empezar."){
                        positiveButton("Empezemos") {startActivity<AnimesSelActivity>()}
                    }.show()

        }else {
            /* Check if no anime is selected */
            if (db.getCountAnimeSel() == 0) {
                alert("No tienes ningún anime seleccionado, ¿Quieres seleccionarlos ahora?", "No hay animes seleccionados") {
                    positiveButton("Si") { startActivity<AnimesSelActivity>() }
                    negativeButton("No") { }
                }.show()
            }
        }

        //For "Vote us in Play Store"
        if (P.getRateCountdown() == 0){
            alert("¿Te gusta la apliación? ¿Crees que la falta algo?"){
                positiveButton("Danos tu opinión") {browse("https://play.google.com/store/apps/details?id=com.jkanetwork.st.frasesdeanime")}
                negativeButton("Más tarde") { }
            }.show()
            P.setRateCountdown(); //To -1, if not..you know
        }else{
            P.setRateCountdown(); //Countdown one
        }


        /* Button listeners */
        btn_fav.setOnClickListener() {
            db.setFav(IDFraseS)
            if (db.getFav(IDFraseS) == true) {
                btn_fav.setBackgroundResource(R.drawable.star_on);
            }else{
                btn_fav.setBackgroundResource(R.drawable.star_off);
            }
        }

        btn_share.setOnClickListener() {
            share("${txt_sentence.text} (${txt_anime.text}) \n ${this.getString(R.string.sharefrom)}")
        }

        btn_change.setOnClickListener() {
            if (mRewardedVideoAd.isLoaded() && IDFraseS > 0) {
                mRewardedVideoAd.show();
            }else if (IDFraseS <= 0) {
                alert("Aquí no puedes ver una frase aún, no sirve de nada pulsar el botón") {
                    positiveButton("Ok") { }
                }.show()
            }else{
                alert("Aún no hay un anuncio disponible, espere") {
                    positiveButton("Ok") { }
                }.show()
                preloadAd()
            }
        }


        //Button for previous day
        btn_prev.setOnClickListener() {
            if (dayS == 1){
                if (monthS == 1){
                    monthS=12
                    yearS -= 1
                }else{
                    monthS -=1
                }
                if (monthS in arrayOf(1, 3, 5,7,8,10,12)){
                    dayS = 31
                }else if (monthS == 2){
                    dayS = 28
                }else{
                    dayS = 30
                }
            }else{
                dayS -=1
            }
            changeData()
        }

        //Button of next (day) sentence
        btn_next.setOnClickListener() {
            if ((monthS in arrayOf(1, 3, 5,7,8,10) && dayS == 31) || (monthS == 2 && dayS == 28) || (monthS in arrayOf(2,4,6,9,11) && dayS == 30)){
                monthS += 1
                dayS = 1
            }else if (dayS == 31 && monthS == 12){ //New Year
                monthS = 1
                dayS = 1
            }else{
                dayS +=1
            }
            changeData()
        }

        btn_today.setOnClickListener(){
            //Go back to today
            dayS = cal.get(Calendar.DAY_OF_MONTH)
            monthS = cal.get(Calendar.MONTH)+1
            yearS = cal.get(Calendar.YEAR)
            changeData()
        }
    }


    /** At onResume, called after onCreate and in resume, load ad things and refresh calendar data */
    override fun onResume() {
        super.onResume()

        txt_sentence.setMovementMethod(ScrollingMovementMethod()) //Make sentence text scrollable

        preloadAd() //Load (Again) ads

        cal = Calendar.getInstance() //Refresh calendar
        //Refresh day
        dayS = cal.get(Calendar.DAY_OF_MONTH)
        monthS = cal.get(Calendar.MONTH)+1
        yearS = cal.get(Calendar.YEAR)
        changeData()
    }

    /** "Close" app on back button */
    override fun onBackPressed() {
        moveTaskToBack(true)
    }

    /** It returns the month name  */
    fun getMonth(month: Int): String {
        val str = DateFormatSymbols().getMonths()[month - 1]
        return str.capitalize()
    }

    /** This function replaces texts of main activity to sentence using IDFraseS var
     */
    fun changeData(){
        IDFraseS = db.getIDFrase(yearS,monthS, dayS)
        txt_sentence.setText(db.getSentenceFromIDF(IDFraseS))
        txt_anime.setText(db.getAnimeFromIDF(IDFraseS))
        //txt_date.setText("Frase de hoy")
        txt_date.setText("Frase del $dayS de ${getMonth(monthS)}")
        /* Set fav icon */
        if (db.getFav(IDFraseS) == true) {
            btn_fav.setBackgroundResource(R.drawable.star_on);
        }else{
            btn_fav.setBackgroundResource(R.drawable.star_off);
        }
    }

    /** This changes sentence of day you are seeing */
    override fun onRewarded(reward: RewardItem) {
        alert {
            customView {
                linearLayout {
                    imageView {
                        imageResource = R.drawable.gato
                    }.lparams(width = matchParent) {
                        margin = dip(4)
                    }
                }
            }
            positiveButton("Cambiar la frase") {
                /* First remove sentence, then load a new one, and change data */
                db.delSentence(yearS,monthS, dayS)
                IDFraseS = db.getIDFrase(yearS,monthS, dayS)
                changeData()
            }
        }.show()
    }


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean{
        when (item.getItemId()) {
            R.id.favs -> {
                startActivity<FavsActivity>()
                return true
            }
            R.id.anime -> {
                startActivity<AnimesSelActivity>()
                return true
            }
            R.id.options -> {
                startActivity<OptsActivity>()
                return true
            }
            R.id.about -> {
                startActivity<AboutActivity>()
                return true
            }
            R.id.exit -> {
                moveTaskToBack(true) /* Returns to "desktop" */
                return super.onOptionsItemSelected(item)
            }
            else -> return super.onOptionsItemSelected(item)
        }
    }


    fun preloadAd() {
        var Adr = AdRequest.Builder()
        Adr.addTestDevice("C0119E16F190120A0481C80734939D71")
        Adr.addTestDevice("4264F289943AD2719C3F0ECB2CD4556A")
        Adr.addTestDevice("D0CF3543C15E51623C67081FA8B64C2B")

        val extras = Bundle()
        extras.putString("max_ad_content_rating", "PG") //Non adult ads

        mRewardedVideoAd.loadAd(this.getString(R.string.admob_videoid), Adr.addNetworkExtrasBundle(AdMobAdapter::class.java, extras).build())
    }

}
