/**
 * 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.activities

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import com.amazon.identity.auth.device.AuthError
import com.amazon.identity.auth.device.api.workflow.RequestContext
import com.amazon.identity.auth.device.api.authorization.AuthorizeResult
import com.amazon.identity.auth.device.api.authorization.AuthCancellation
import com.amazon.identity.auth.device.api.authorization.AuthorizeListener
import com.nxp.vizncompanionapp.adapters.ListAdapter
import com.nxp.vizncompanionapp.viewModel.DeviceViewModel
import com.nxp.vizncompanionapp.model.Device
import com.nxp.vizncompanionapp.utility.AppConstant
import com.nxp.vizncompanionapp.utility.DisplayNotifications
import com.nxp.vizncompanionapp.utility.NetworkChangeReceiver
import com.nxp.vizncompanionapp.utility.PreferencesHelper

class DeviceListingActivity : AppCompatActivity() {

    private var requestContext: RequestContext? = null
    private val CODE_CHALLENGE_METHOD = "S256"
    var adapter : ListAdapter? = null
    private var mDeviceViewModel: DeviceViewModel? = null
    private var currentDevice: Device? = null
    var prefeernce: PreferencesHelper? = null
    private var mDisplayNotifications: DisplayNotifications = DisplayNotifications()
    /**
     * Object of NetworkChangeReceiver to start and stop timer
     */
    private val networkChangeReceiver = NetworkChangeReceiver()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
/*        setContentView(R.layout.activity_device_listing)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        //Amazon Login page stuff
        requestContext = RequestContext.create(this)
        requestContext?.registerListener(AuthorizeListenerImpl())
        this.prefeernce = PreferencesHelper(this)


        adapter = ListAdapter(this)
        rvDeviceList.adapter = adapter
        rvDeviceList.layoutManager = LinearLayoutManager(this)

        // Get a new or existing ViewModel from the ViewModelProvider.
        mDeviceViewModel = ViewModelProviders.of(this).get(DeviceViewModel::class.java)

        // Add an observer on the LiveData returned by getAlphabetizedWords.
        // The onChanged() method fires when the observed data changes and the activity is
        // in the foreground.
        mDeviceViewModel?.getAllDevices()?.observe(this, Observer { devices ->
            // Update the cached copy of the words in the adapter.
            adapter?.setDevices(devices)
        })
        getDevice()
        onClickListener()*/
    }

    /**
     * get devices which are in LAN
     */
    fun getDevice(){
/*        mDeviceViewModel?.sendBroadcast(this)
        mDeviceViewModel?.loadDevices(this)*/
    }

    private fun onClickListener() {
/*        adapter?.setOnItemClickListener(object : ListAdapter.MyClickListener {
            override fun onItemClick(position: Int, v: View , mDeviceList: List<Device>?) {
                val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
                if(pm.isPowerSaveMode && !pm!!.isIgnoringBatteryOptimizations(packageName)){
                    Log.e("TAG","Power Save Mode On")
                    mDeviceViewModel?.displayBatterySaverDialog(this@DeviceListingActivity)
                } else {
                    if (prefeernce?.loadSavedBooleanPreferences(AppConstant.SHARED_KEY_LINKING_PROCESS)!!) {
                        mDeviceViewModel?.displayLinkingProcessDialog(this@DeviceListingActivity)
                    } else {
                        if(mDeviceList?.get(position)?.mState == AppConstant.DEVICE_STATE_CONFIRM_RESPONSE) {
                            val scopeData = JSONObject()
                            val productInstanceAttributes = JSONObject()
                            try {
                                currentDevice = mDeviceList?.get(position)
                                mDeviceViewModel?.updateDeviceDetails(Device(mDeviceList?.get(position)?.mProductID!!, mDeviceList?.get(position)?.mDsn, mDeviceList?.get(position)?.mCodeChallenge, mDeviceList?.get(position)?.mState, mDeviceList?.get(position)?.mDeviceAddress, AppConstant.DEVICE_AMAZON_REQUEST,mDeviceList?.get(position)?.mMetadata), this@DeviceListingActivity)
                                productInstanceAttributes.put("deviceSerialNumber", mDeviceList?.get(position)?.mDsn)
                                scopeData.put("productInstanceAttributes", productInstanceAttributes)
                                scopeData.put("productID", mDeviceList?.get(position)?.mProductID)
*//*                                AuthorizationManager.authorize(
                                        AuthorizeRequest.Builder(requestContext)
                                                .addScope(ScopeFactory.scopeNamed("alexa:all", scopeData))
                                                .forGrantType(AuthorizeRequest.GrantType.AUTHORIZATION_CODE)
                                                .withProofKeyParameters(mDeviceList?.get(position)?.mCodeChallenge, CODE_CHALLENGE_METHOD)
                                                .build()
                                )*//*
                                mDeviceViewModel?.getIPAddress(mDeviceList?.get(position)?.mDeviceAddress!!)
                            } catch (e: Exception) {
                                Log.e("TAG", e.toString())
                            }
                        } else {
                            if(mDeviceList?.get(position)?.mState == "") {
                                currentDevice = mDeviceList?.get(position)
                                mDisplayNotifications?.displayErrorDialog(this@DeviceListingActivity,getString(R.string.device_action_msg),getString(R.string.update),getString(R.string.onboard))
                                mDeviceViewModel?.getIPAddress(mDeviceList?.get(position)?.mDeviceAddress!!)
                            }
                        }
                    }
                }
            }
        })*/
    }

    fun updateWifiCredentials(){
/*        intent = Intent(this, WifiListingActivity::class.java)
        intent.putExtra("action", "update_mode")
        intent.putExtra("ipAddress", currentDevice?.mDeviceAddress)
        startActivity(intent)
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
        finish()*/
    }

    fun sendConfirmRequest(){
       // mDeviceViewModel?.sendConfirmationRequest(this@DeviceListingActivity)
    }


    override fun onResume() {
        super.onResume()
/*        requestContext?.onResume()
        networkChangeReceiver.setTimer(this)
        if(prefeernce?.loadSavedBooleanPreferences(AppConstant.SHARED_KEY_WIFI_LOST)!!){
            mDeviceViewModel?.stopSocket()
            mDeviceViewModel?.removeHandlerSend()
            mDeviceViewModel?.removeHandlerRequest()
            prefeernce?.savePreferences(AppConstant.SHARED_KEY_WIFI_LOST,false)
            getDevice()
        }*/
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        return super.onOptionsItemSelected(item)
/*        return if (item?.itemId == android.R.id.home) {
            onBackPressed()
            true
        } else {
            super.onOptionsItemSelected(item)
        }*/
    }

    override fun onDestroy() {
        super.onDestroy()
/*        networkChangeReceiver.stopTimer()
        mDeviceViewModel?.stopSocket()
        mDeviceViewModel?.removeHandlerSend()
        mDeviceViewModel?.stopTimer()
        mDeviceViewModel?.removeHandlerRequest()*/
    }

    override fun onBackPressed() {
        super.onBackPressed()
/*        networkChangeReceiver.stopTimer()
        mDeviceViewModel?.stopSocket()
        mDeviceViewModel?.removeHandlerSend()
        mDeviceViewModel?.stopTimer()
        mDeviceViewModel?.removeHandlerRequest()
        finish()
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)*/
    }

    private inner class AuthorizeListenerImpl : AuthorizeListener() {

        /* Authorization was completed successfully. */
        override fun onSuccess(authorizeResult: AuthorizeResult) {
            mDeviceViewModel?.updateDeviceDetails(Device("","","","", currentDevice?.mDeviceAddress!!,AppConstant.DEVICE_AMAZON_RESPONSE,""),this@DeviceListingActivity)
            var authorizationCode = authorizeResult.authorizationCode
            var redirectUri = authorizeResult.redirectURI
            var clientId = authorizeResult.clientId
            mDeviceViewModel?.sendAuthCode(authorizationCode,redirectUri,clientId,this@DeviceListingActivity)
        }

        /* There was an error during the attempt to authorize the application. */
        override fun onError(authError: AuthError) {
            Log.e("TAG",authError?.localizedMessage)
            mDeviceViewModel?.updateDeviceDetails(Device("","","","", currentDevice?.mDeviceAddress!!,AppConstant.DEVICE_STATUS_CONNECTION_ERROR,""),this@DeviceListingActivity)
        }

        /* Authorization was cancelled before it could be completed. */
        override fun onCancel(authCancellation: AuthCancellation) {
            Log.e("TAG",authCancellation.toString())
            mDeviceViewModel?.updateDeviceDetails(Device("","","","", currentDevice?.mDeviceAddress!!,AppConstant.DEVICE_STATUS_CONNECTION_ERROR,""),this@DeviceListingActivity)
        }
    }

}
