package com.jld.vod.view

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.observe
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.jld.vod.R
import com.jld.vod.base.BaseActivity
import com.jld.vod.config.Config
import com.jld.vod.model.bean.ModelAllBean
import com.jld.vod.service.LatLongService
import com.jld.vod.service.PositionAdvertService
import com.jld.vod.ui.animator.HomeRatateImage
import com.jld.vod.utils.DateUtils
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.SharedPrefUtils
import com.jld.vod.viewmodel.MainViewModel
import com.jld.vod.viewmodel.SplashViewModel
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import com.zhy.view.CircleMenuLayout
import kotlinx.android.synthetic.main.activity_home.*
import java.lang.Exception
import java.util.*


/**
 * 旋转功能菜单界面
 */
class HomeActivity : BaseActivity() {
    private var mCircleMenuLayout: CircleMenuLayout? = null
    private var iv_home_center: ImageView? = null
    //private var receiver: broadCastRecever = broadCastRecever()//更新时间广播
    private lateinit var viewModel: MainViewModel
    private val homedata: MutableList<String> = ArrayList()
    private var ratateImage: HomeRatateImage? = null
    private var animation:ScaleAnimation? =null
    private var gpsService:Boolean = true

    private val mItemTexts = arrayOf(
        "电影 ", "音乐", "游戏",
        "浏览器 ", "地图", "关于"
    )
    private val mItemImgs = intArrayOf(
        R.mipmap.home_movie, R.mipmap.home_music,
        R.mipmap.home_game, R.mipmap.home_browser,
        R.mipmap.home_maps, R.mipmap.home_settings)

    override fun initView() {
        super.initView()


        //开启获取经纬度服务
        startService(Intent(this,LatLongService::class.java))
        //开启固定广告服务
        startService(Intent(this,PositionAdvertService::class.java))

        //初始化mainviewmodel
        viewModel =ViewModelProvider.AndroidViewModelFactory(application).create(MainViewModel::class.java)

        //待机
        iv_home_power.setOnClickListener {
            fl_bg.visibility = View.VISIBLE
        }
        iv_fl_power.setOnClickListener {
            fl_bg.visibility = View.INVISIBLE
        }
        iv_home.setOnClickListener {
            //    addNotification("Nihao")
        }
        //解决穿透问题
        fl_bg.setOnTouchListener(object :View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                return true
            }
        })
        //点击logo5次跳转设置
        ll_date_time.setOnClickListener {
            HideClick().start()
            if (HideClick.sIsAlive >= 5) {
                bulletFrameSetting()
            }
        }

        //初始化背景图
        mCircleMenuLayout =  findViewById(R.id.id_menulayout)
        iv_home_center =  findViewById(R.id.iv_home_center)
        val main_bg_img = SharedPrefUtils.getString(this,"main_bg_img")
        val main_logo= SharedPrefUtils.getString(this,"main_logo")

        try {
            if (!main_logo.isEmpty())
            {
                Glide.with(this).load(com.jld.vod.config.Config.ApiBaseUrl+"/synchronization/previewImg?imgUrl="
                        +main_logo).into(iv_home_center!!)
            }

            if (!main_bg_img.isEmpty())
            {
                val simpleTarget: SimpleTarget<Drawable?> = object : SimpleTarget<Drawable?>() {
                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable?>?) {
                        ll_home.setBackground(resource)
                    }
                }
                Glide.with(this).load(com.jld.vod.config.Config.ApiBaseUrl+"/synchronization/previewImg?imgUrl="
                        +main_bg_img).into(simpleTarget)
            }
        }catch (e:Exception)
        {
            e.printStackTrace()
        }

        ratateImage = HomeRatateImage(this, iv_home_center)
        viewModel.getAllModular()
        // 以view中心为缩放点，由初始状态缩小两倍
        animation = ScaleAnimation(
                1.0f, 0.0f, 1.0f, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        animation!!.setDuration(1500)
        animation!!.setRepeatCount(0)
        animation!!.setFillAfter(!animation!!.getFillAfter());
    }
    override fun initData() {
        super.initData()

        /**
         * 全部模块
         */

        viewModel.ByrtNamesLiveData.observe(this){ res->
            if (res != null)
            {
                for ((index,data) in res.withIndex())
                {
                    homedata.add(Config.ApiBaseUrl+"/synchronization/previewImg?imgUrl="+data.imgUrl)
                }

                mCircleMenuLayout!!.setMenuItemIconsAndTexts(homedata, mItemTexts)
                mCircleMenuLayout!!.setOnMenuItemClickListener(object :
                        CircleMenuLayout.OnMenuItemClickListener {
                    override fun itemClick(view: View?, pos: Int) {

                        val bpos = Bundle()
                        bpos.putInt("pos", pos)
                        //旋转动画
                        ratateImage!!.startSpin()

                        animation!!.setAnimationListener(object :Animation.AnimationListener{
                            override fun onAnimationRepeat(animation: Animation?) {}
                            override fun onAnimationEnd(animation: Animation?) {
                                ratateImage!!.stopSpin()
                                go<MainActivity>(bpos)
                            }
                            override fun onAnimationStart(animation: Animation?) {}
                        })

                        iv_home_center!!.startAnimation(animation)

                    }

                    override fun itemCenterClick(view: View?) {
                        Toast.makeText(applicationContext, "you can do something just like ccb  ", Toast.LENGTH_SHORT).show()
                    }
                })
            }
        }

    }

    override fun onResume() {
        super.onResume()
        if (animation != null)
        {
             animation!!.cancel()
        }
    }


    /**
     * 弹框方法
     */
    private fun bulletFrameSetting(){
        MaterialDialog.Builder(this)
            .title("Password")
            .inputType(
                InputType.TYPE_CLASS_TEXT
                        or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                        or InputType.TYPE_TEXT_FLAG_CAP_WORDS
            )
            .input("Please enter your password", "", false,
                MaterialDialog.InputCallback { dialog: MaterialDialog?, input: CharSequence ->
                    if (input.toString() == Config.pwd) {
                        val mIntent = Intent(applicationContext, SettingsActivity::class.java)
                        mIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        startActivity(mIntent)
                    }else{
                        bulletFrameSetting()
                        Toast.makeText(this,"PassWord Error",Toast.LENGTH_LONG).show()
                    }
                }
            )
            .inputRange(5, 10)
            .positiveText("Confirm")
            .negativeText("Cancel")
            .cancelable(false)
            .show()
    }
    override fun getLayoutId(): Int {
        return R.layout.activity_home
    }
    override fun onStart() {
        super.onStart()
        LogUtils.logD("DD初始化当前时间")
//        //初始化当前时间
//        var dateString =  SharedPrefUtils.getString(this,"newDate")
//        Log.d("onStart", "onStart: $dateString")
//        Log.d("onStart——系统时间", "onStart:"+System.currentTimeMillis())
        var date: Date = Date(System.currentTimeMillis())
//        var dateLong =0L
//        try {
//            dateLong = dateString.toLong()
//        } catch ( e : NumberFormatException){
//            Log.e( "","onStart: ", e)
//        }
//        //初始化当前时间
//        var date: Date = Date(dateLong)
        var time = DateUtils.getTime(date)
        var dates = DateUtils.getDate(date)
        var week = DateUtils.getWeekOfDate(date)
        tv_main_time.text = time
        tv_main_week.text = dates +" "+ week
//        //动态注册广播
//        val filter = IntentFilter()
//        filter.addAction(Intent.ACTION_TIME_TICK)
//        registerReceiver(receiver, filter)
    }
    override fun onDestroy() {
        super.onDestroy()
      //  unregisterReceiver(receiver)
    }

    /**
     * 时间广播更新
     */
    inner class broadCastRecever : BroadcastReceiver() {
        //广播接收器
        override fun onReceive(context: Context?, intent: Intent?) {//接收广播后执行的操作
            var action: String? = intent!!.action
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                //获取当前时间
                var date: Date = Date(System.currentTimeMillis())
                var time = DateUtils.getTime(date)
                var dates = DateUtils.getDate(date)
                var week = DateUtils.getWeekOfDate(date)
                tv_main_time.text = time
                tv_main_week.text = dates + " " +week
            }
        }
    }
    internal class HideClick : Thread() {
        override fun run() {
            sIsAlive++
            try {
                sleep(3000)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            if (sIsAlive > 0) {
                sIsAlive--
            }
            super.run()
        }
        companion object {
            @Volatile
            var sIsAlive = 0
        }
    }
}