/**
 * Copyright (c) 2018 NXP
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * o Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.nxp.vizncompanionapp.utility

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.PowerManager
import android.provider.Settings
import android.text.InputType
import android.text.method.PasswordTransformationMethod
import android.view.LayoutInflater
import com.afollestad.materialdialogs.MaterialDialog
import com.nxp.vizncompanionapp.R
import com.nxp.vizncompanionapp.activities.*
import kotlinx.android.synthetic.main.wifi_password_dialog.view.*

class DisplayNotifications {

    /**
     * Material dialog, all level compatible
     */
    private var builder: MaterialDialog.Builder? = null
    private var materialDialog: MaterialDialog? = null

    /**
     * Display Please wait Dialog
     *
     * @param context Context of Activity
     */
    fun fetchData(context: Context){
        dismissDialog()
        builder = MaterialDialog.Builder(context)
        builder?.cancelable(false)
        builder?.progress(true, 0)
        builder?.contentColor(Color.BLACK)
        builder?.widgetColor(context.getColor(R.color.colorPrimary))
        builder?.content(context.getString(R.string.please_wait))
        materialDialog = builder?.build()
        try {
            materialDialog?.show()
        } catch (e: Exception) {
        }

    }

    fun displayPermissionsRequest(context: Context){
        val pm = context.getSystemService(PowerManager::class.java)
        val pkgName = context.packageName
        if (!pm!!.isIgnoringBatteryOptimizations(pkgName)) {
            val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
                    .setData(Uri.parse("package:$pkgName"))

            context.startActivity(intent)
        }
    }

    /**
     * Dismiss Any dialog
     */
    fun dismissDialog(){
        if (materialDialog != null) {
            materialDialog?.dismiss()
            materialDialog = null
            builder = null
        } else {

        }
    }

    /**
     * Display Dialog which indicates list id empty
     *
     * @param context Context of Activity
     */
    fun emptyDataDialog(context: Context?, string: String?, positive: String?, negative: String?){
        dismissDialog()
        builder = MaterialDialog.Builder(context!!)
        builder?.cancelable(false)
        builder?.positiveColor(context.getColor(R.color.colorPrimary))
        builder?.negativeColor(context.getColor(R.color.colorPrimary))
        builder?.positiveText(positive!!)
        builder?.negativeText(negative!!)
        builder?.content(string!!)
        builder?.contentColor(context.getColor(android.R.color.black))
        builder?.onPositive{dialog, which ->
            dialog.dismiss()
            if(context is DeviceIpActivity){
                context.getDevice()
            } else if (context is DiscoverActivity){
                context.getDevice()
            }
        }
        builder?.onNegative { dialog, which ->
            dialog.dismiss()
            if(context is DeviceIpActivity){
                context.onBackPressed()
            }
        }
        materialDialog = builder?.build()
        try {
            materialDialog?.show()
        } catch (e: Exception) {
        }
    }

    /**
     * Display Dialog which indicates Linking Timeout
     *
     * @param context Context of Activity
     */
    fun displayErrorDialog(context: Context?, string: String?, positive: String?, negative: String?){
        dismissDialog()
        builder = MaterialDialog.Builder(context!!)
        builder?.cancelable(false)
        builder?.positiveColor(context.getColor(R.color.colorPrimary))
        builder?.negativeColor(context.getColor(R.color.colorPrimary))
        builder?.positiveText(positive!!)
        builder?.negativeText(negative!!)
        builder?.content(string!!)
        builder?.contentColor(context.getColor(android.R.color.black))
        builder?.onPositive{dialog, which ->
            dialog.dismiss()
            if(context is DeviceListingActivity){
                when (string) {
                    context.getString(R.string.confirm_request_fail_msg) -> context.sendConfirmRequest()
                    context.getString(R.string.device_action_msg) -> context.updateWifiCredentials()
                    else -> context.getDevice()
                }
            } else if(context is WifiListingActivity){
                when (string) {
                    context.getString(R.string.permission_location_access) -> context.requestLocationPermissions()
                    context.getString(R.string.permissions_not_granted) -> context.goToSettings()
                    context.getString(R.string.permission_gps_access) -> context.turnOnGpsRequest()
                    context.getString(R.string.bt_require_msg) -> context.turnOnBLERequest()
                    else -> {
                        if(string?.contains("Please connect with")!!){
                            context.turnOnWifiRequest()
                        }
                    }
                }
            } else if(context is BleListingActivity){
                when (string) {
                    context.getString(R.string.permission_location_access) -> context.requestLocationPermissions()
                    context.getString(R.string.permissions_not_granted) -> context.goToSettings()
                    context.getString(R.string.permission_gps_access) -> context.turnOnGpsRequest()
                    context.getString(R.string.bt_require_msg) -> context.turnOnBLERequest()
                    context.getString(R.string.ble_list_empty_msg) -> context.startScanProcess()
                    else -> {
                        if(string?.contains("Please connect with")!!){
                            //context.turnOnWifiRequest()
                        }
                    }
                }
            } else if (context is DiscoverActivity){
                //TODO
                //context.getDevice()
                if(string == context.getString(R.string.invalid_data)){
                    context.getDevice()
                } else if (string == context.getString(R.string.bt_require_msg)){
                    context.turnOnBLERequest()
                }
            }
        }
        builder?.onNegative { dialog, which ->
            dialog.dismiss()
            if(context is DeviceListingActivity){
                if(string == context.getString(R.string.device_action_msg)){
                    context.sendConfirmRequest()
                } else {
                    context.onBackPressed()
                }
            } else if (context is WifiListingActivity){
                when (string) {
                    context.getString(R.string.permission_location_access) -> context.onBackPressed()
                    context.getString(R.string.permissions_not_granted) -> context.onBackPressed()
                    context.getString(R.string.permission_gps_access) -> context.onBackPressed()
                    context.getString(R.string.bt_require_msg) -> context.onBackPressed()
                }
            } else if (context is BleListingActivity){
                when (string) {
                    context.getString(R.string.permission_location_access) -> context.onBackPressed()
                    context.getString(R.string.permissions_not_granted) -> context.onBackPressed()
                    context.getString(R.string.permission_gps_access) -> context.onBackPressed()
                    context.getString(R.string.bt_require_msg) -> context.onBackPressed()
                    context.getString(R.string.ble_list_empty_msg) -> context.onBackPressed()
                }
            }
        }
        materialDialog = builder?.build()
        try {
            materialDialog?.show()
        } catch (e: Exception) {
        }
    }

    /**
     * Display Dialog which indicates Linking Process
     *
     * @param context Context of Activity
     */
    fun displayLinkingProcessDialog(context: Context?, string: String){
        dismissDialog()
        builder = MaterialDialog.Builder(context!!)
        builder?.cancelable(false)
        builder?.positiveColor(context.getColor(R.color.colorPrimary))
        builder?.negativeColor(context.getColor(R.color.colorPrimary))
        builder?.positiveText(context.getString(R.string.ok))
        builder?.content(string)
        builder?.contentColor(context.getColor(android.R.color.black))
        builder?.onPositive{dialog, which ->
            dialog.dismiss()
            if(context is WifiListingActivity){
                context.onBackPressed()
            }
        }
        materialDialog = builder?.build()
        try {
            materialDialog?.show()
        } catch (e: Exception) {
        }
    }

    fun displayBatterySaverDialog(context: Context?){
        dismissDialog()
        builder = MaterialDialog.Builder(context!!)
        builder?.cancelable(false)
        builder?.positiveColor(context.getColor(R.color.colorPrimary))
        builder?.negativeColor(context.getColor(R.color.colorPrimary))
        builder?.positiveText(context.getString(R.string.ok))
        builder?.content(context.getString(R.string.battery_saver_msg))
        builder?.contentColor(context.getColor(android.R.color.black))
        builder?.onPositive{dialog, which ->
            dialog.dismiss()
            displayPermissionsRequest(context)
        }
        materialDialog = builder?.build()
        try {
            materialDialog?.show()
        } catch (e: Exception) {
        }
    }

    fun displayWiFiPasswordDialog(context: Context, ssid: String, ipAddress: String, s: String, type: String?){
        dismissDialog()
        builder = MaterialDialog.Builder(context!!)
        builder?.cancelable(false)
        val mDialogView = LayoutInflater.from(context).inflate(R.layout.wifi_password_dialog, null)
        builder?.customView(mDialogView,false)
        if(s == "wifi") {
            mDialogView.dialogWiFiNameEt.hint = "Enter WiFi Name"
        } else {
            mDialogView.dialogWiFiNameEt.hint = "Enter Hotspot Name"
        }
        if(ssid != "") {
            mDialogView.dialogWiFiNameEt.isEnabled = false
            mDialogView.dialogWiFiNameEt.setText(ssid)
        } else {
            mDialogView.dialogWiFiNameEt.isEnabled = true
        }
        materialDialog = builder?.build()
        try {
            materialDialog?.show()
        } catch (e: Exception) {
        }
        mDialogView.dialogSendBtn.setOnClickListener {
            if(mDialogView.dialogWiFiPasswordEt.text.length < 8){
                mDialogView.dialogWiFiPasswordEt.error = context.getString(R.string.password_error)
            } else {
                if(context is WifiListingActivity){
                    materialDialog?.dismiss()
                    context.SendCredtoDevice(context, ipAddress, mDialogView.dialogWiFiNameEt.text.toString(), mDialogView.dialogWiFiPasswordEt.text.toString(),type)
                }
            }
        }
        mDialogView.dialogCancelBtn.setOnClickListener {
            materialDialog?.dismiss()
        }
        mDialogView.dialogPasswordCb.setOnCheckedChangeListener { _, isChecked ->
            mDialogView.dialogWiFiPasswordEt.inputType = if (!isChecked) InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_CLASS_TEXT
            mDialogView.dialogWiFiPasswordEt.transformationMethod = if (!isChecked) PasswordTransformationMethod.getInstance() else null
            mDialogView.dialogWiFiPasswordEt.setSelection(if (!isChecked)  mDialogView.dialogWiFiPasswordEt.text.length else  mDialogView.dialogWiFiPasswordEt.text.length)
        }
    }
}