package com.kdanmobile.reader.setting

import android.app.Dialog
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.widget.CompoundButton
import com.kdanmobile.reader.R
import com.kdanmobile.reader.screen.model.SharePrefsModel
import android.support.v7.app.AlertDialog
import android.support.v7.widget.Toolbar
import android.view.*
import com.kdanmobile.reader.screen.view.*

open class ReaderSettingDialogFragment : DialogFragment() {

    private lateinit var viewModel: ReaderSettingViewModel
    private val isReaderSettingFullScreen by lazy { resources.getBoolean(R.bool.isReaderSettingFullScreen) }

    private lateinit var toolbar_viewerSetting: Toolbar
    private lateinit var readingModeSelectView: ReadingModeSelectView
    private lateinit var turnPageModeSelectView: TurnPageModeSelectView
    private lateinit var screenSettingView: ScreenSettingView
    private lateinit var toolbarSettingView: ToolbarSettingView
    private lateinit var rowSwitchView_smartCrop: RowSwitchView
    private lateinit var rowSwitchView_showStateBar: RowSwitchView

    private var readerSettingListener: ReaderSettingListener? = null
        get() = if (activity is ReaderSettingListener) (activity as ReaderSettingListener) else null
    private var initialized = true

    protected open fun hasPermissionToUseSmartCrop(): Boolean { return false }
    protected open fun hasPermissionToChangeTheme(): Boolean { return false }
    protected open fun onNoPermissionToUseSmartCrop() {}
    protected open fun onNoPermissionToChangeTheme() {}

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val view = LayoutInflater.from(context).inflate(R.layout.activity_reader_setting, null)
        initViews(view)
        initViewModel()

        val dialog: Dialog
        if (isReaderSettingFullScreen) {
            dialog = Dialog(activity!!)
            dialog.window?.requestFeature(Window.FEATURE_NO_TITLE)
            dialog.setContentView(view)
            dialog.window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT)
            dialog.window?.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
            if (viewModel.isShowStateBarEnable.value == true) {
                dialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
            }
        } else {
            val builder = AlertDialog.Builder(activity!!)
            dialog = builder.show()
            dialog.setContentView(view)
        }
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        return dialog
    }

    override fun onResume() {
        super.onResume()
        initialized = false
    }

    private fun initViewModel() {
        viewModel = ViewModelProviders.of(this, ReaderSettingViewModelFactory(SharePrefsModel(requireContext())))
                .get(ReaderSettingViewModel::class.java)

        viewModel.readMode.observe(this, Observer(this::onReadModeChanged))
        viewModel.isCropModeEnable.observe(this, Observer(this::onCropModeEnableChanged))
        viewModel.isShowStateBarEnable.observe(this, Observer(this::onShowStateBarEnableChanged))
        viewModel.turnPageDirection.observe(this, Observer(this::onTurnPageDirectionChanged))
        viewModel.isShowTurnPageBtnEnable.observe(this, Observer(this::onShowTurnPageBtnEnableChanged))
        viewModel.isLockScreenSleepEnable.observe(this, Observer(this::onLockScreenSleepEnableChanged))
        viewModel.isShowCommentToolEnable.observe(this, Observer(this::onShowCommentToolEnableChanged))
        viewModel.isShowBOTAToolEnable.observe(this, Observer(this::onShowBOTAToolEnableChanged))
    }

    private fun initViews(view: View) {
        toolbar_viewerSetting = view.findViewById(R.id.toolbar_viewerSetting)
        readingModeSelectView = view.findViewById(R.id.readingModeSelectView)
        turnPageModeSelectView = view.findViewById(R.id.turnPageModeSelectView)
        screenSettingView = view.findViewById(R.id.screenSettingView)
        toolbarSettingView = view.findViewById(R.id.toolbarSettingView)
        rowSwitchView_smartCrop = view.findViewById(R.id.rowSwitchView_smartCrop)
        rowSwitchView_showStateBar = view.findViewById(R.id.rowSwitchView_showStateBar)

        setupToolbar()
        setupReadingModeView()
        setupTurnPageView()
        setupScreenSettingView()
        setupToolbarSettingView()

        rowSwitchView_smartCrop.onCheckedChangeListener = CompoundButton.OnCheckedChangeListener { _, isChecked ->
            if (viewModel.isCropModeEnable.value == isChecked) return@OnCheckedChangeListener
            if (isChecked && !hasPermissionToUseSmartCrop()) {
                rowSwitchView_smartCrop.isChecked = false
                onNoPermissionToUseSmartCrop()
                return@OnCheckedChangeListener
            }
            viewModel.setCropModeEnable(isChecked)
            if (!initialized) {
                readerSettingListener?.onCropModeEnableChanged(isChecked)
            }
        }
        rowSwitchView_showStateBar.onCheckedChangeListener = CompoundButton.OnCheckedChangeListener { _, isChecked ->
            viewModel.setShowStateBarEnable(isChecked)
            if (!initialized) {
                readerSettingListener?.onShowStateBarEnableChanged(isChecked, dialog)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        readerSettingListener = null
    }

    private fun setupToolbar() {
        toolbar_viewerSetting.setNavigationOnClickListener {
            dismiss()
        }
    }

    private fun setupReadingModeView() {
        readingModeSelectView.isLock = !hasPermissionToChangeTheme()
        readingModeSelectView.onReadModeSelectListener = object : ReadingModeSelectView.OnReadModeSelectListener {
            override fun onReadModeSelect(readMode: Int) {
                viewModel.setReadMode(readMode)
                if (!initialized) {
                    readerSettingListener?.onReadModeChanged(readMode)
                }
            }
        }
        readingModeSelectView.onClickLockedItemListener = object : ReadingModeSelectView.OnClickLockedItemListener {
            override fun onClickLockedItem() {
                onNoPermissionToChangeTheme()
            }
        }
    }

    private fun setupTurnPageView() {
        turnPageModeSelectView.onTurnPageModeChangedListener = object : TurnPageModeSelectView.OnTurnPageModeChangedListener {
            override fun onTurnPageModeChanged(direction: Int) {
                viewModel.setTurnPageDirection(direction)
                if (!initialized) {
                    readerSettingListener?.onTurnPageDirectionChanged(direction)
                }
            }
        }
        turnPageModeSelectView.onShowTurnPageBtnEnableChangedListener = CompoundButton.OnCheckedChangeListener { _, isChecked ->
            viewModel.setTurnPageButtonEnable(isChecked)
            if (!initialized) {
                readerSettingListener?.onShowTurnPageBtnEnableChanged(isChecked)
            }
        }
    }

    private fun setupScreenSettingView() {
        screenSettingView.onCheckedChangeListener = CompoundButton.OnCheckedChangeListener { _, isChecked ->
            viewModel.setLockScreenSleepEnable(isChecked)
            if (!initialized) {
                readerSettingListener?.onLockScreenSleepEnableChanged(isChecked)
            }
        }
    }

    private fun setupToolbarSettingView() {
        toolbarSettingView.onCheckedChangeListenerComment = CompoundButton.OnCheckedChangeListener { _, isChecked ->
            viewModel.setShowCommentToolEnable(isChecked)
            if (!initialized) {
                readerSettingListener?.onShowCommentToolEnableChanged(isChecked)
            }
        }
        toolbarSettingView.onCheckedChangeListenerBOTA = CompoundButton.OnCheckedChangeListener { _, isChecked ->
            viewModel.setShowBOTAToolEnable(isChecked)
            if (!initialized) {
                readerSettingListener?.onShowBOTAToolEnableChanged(isChecked)
            }
        }
    }

    private fun onReadModeChanged(readMode: Int?) {
        readMode?.let {
            readingModeSelectView.currentReadMode = it
        }
    }

    private fun onCropModeEnableChanged(enable: Boolean?) {
        enable?.let {
            rowSwitchView_smartCrop.isChecked = it
        }
    }

    private fun onShowStateBarEnableChanged(enable: Boolean?) {
        enable?.let {
            rowSwitchView_showStateBar.isChecked = it
        }
    }

    private fun onTurnPageDirectionChanged(direction: Int?) {
        direction?.let {
            turnPageModeSelectView.direction = it
        }
    }

    private fun onShowTurnPageBtnEnableChanged(enable: Boolean?) {
        enable?.let {
            turnPageModeSelectView.isTurnPageBtnEnable = it
        }
    }

    private fun onLockScreenSleepEnableChanged(enable: Boolean?) {
        enable?.let {
            screenSettingView.isLockScreenSleepEnable = it
        }
    }

    private fun onShowCommentToolEnableChanged(enable: Boolean?) {
        enable?.let {
            toolbarSettingView.isShowCommentToolEnable = it
        }
    }

    private fun onShowBOTAToolEnableChanged(enable: Boolean?) {
        enable?.let {
            toolbarSettingView.isShowBOTAToolEnable = it
        }
    }
}
