/**
 * 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.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import com.nxp.vizncompanionapp.R
import com.nxp.vizncompanionapp.utility.DisplayNotifications
import com.nxp.vizncompanionapp.viewModel.DeviceViewModel
import kotlinx.android.synthetic.main.activity_discover.*
import kotlinx.android.synthetic.main.content_discover.*
import android.widget.Toast
import com.nxp.vizncompanionapp.viewModel.BLEViewModel


class DiscoverActivity : AppCompatActivity() {

    /**
     * Object of NetworkChangeReceiver to start and stop timer
     */
    private var mDisplayNotifications: DisplayNotifications = DisplayNotifications()
    private var lastClick: Long = 0
    private var mDeviceViewModel: DeviceViewModel? = null
    private var mBLEViewModel: BLEViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_discover)
        setSupportActionBar(toolbar)

        mDisplayNotifications.displayPermissionsRequest(this)


        mDeviceViewModel = ViewModelProviders.of(this).get(DeviceViewModel::class.java)

        mBLEViewModel = ViewModelProviders.of(this).get(BLEViewModel()::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.
            if(devices?.size!! >= 1) {
                if (devices?.get(0)?.mDeviceAddress ==  mDeviceViewModel?.getIpAddOfWiFi(this,"ipAddress")) {
                    if (devices?.get(0).mMetadata == "metadata") {
                        mDeviceViewModel?.stopSocket()
                        intent = Intent(this, DeviceIpActivity::class.java)
                        startActivity(intent)
                        intent = Intent(this, WifiListingActivity::class.java)
                        intent.putExtra("action", "ap_mode")
                        intent.putExtra("ipAddress",  mDeviceViewModel?.getIpAddOfWiFi(this,"ipAddress"))
                        startActivity(intent)
                        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                    } else {
                        Toast.makeText(this, getString(R.string.invalid_data), Toast.LENGTH_LONG).show()
                    }
                } else {
                    Toast.makeText(this, getString(R.string.invalid_data), Toast.LENGTH_LONG).show()
                }
            }
            Log.e("TAG","Size "+devices?.size)
        })
        onClickListener()
    }

    fun getDevice(){
        if(mDeviceViewModel?.checkWiFiConnection(this)!!) {
            mDeviceViewModel?.sendMsgToWiFiConnectedDevice(this, mDeviceViewModel?.getIpAddOfWiFi(this,"ipAddress")!!)
            mDeviceViewModel?.loadDevices(this)
        } else {
            Log.e("TAG","wifi off")
            mDisplayNotifications?.displayLinkingProcessDialog(this,getString(R.string.wifi_off_msg))
        }
    }

    private fun onClickListener() {
/*        btnDiscover.setOnClickListener {

            if (SystemClock.elapsedRealtime() - lastClick >= 1000){
                intent = Intent(this, DeviceListingActivity::class.java)
                intent.putExtra("action","broadcast")
                startActivity(intent)
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                lastClick = SystemClock.elapsedRealtime()
            }
        }*/

        btnWiFiProvision.setOnClickListener {
            getDevice()
        }

        btnBleProvision.setOnClickListener {
            if(!mBLEViewModel?.checkForBLE(this)!!){
                Toast.makeText(this,getString(R.string.bluetooth_not_support_msg),Toast.LENGTH_SHORT).show()
            } else {
                mBLEViewModel?.checkBLEState(this)
            }
        }

//        btnGetIp.setOnClickListener {
//            intent = Intent(this, DeviceIpActivity::class.java)
//            intent.putExtra("action","broadcast")
//            startActivity(intent)
//            //mDeviceViewModel?.sendBroadcast(this)
//            //mDeviceViewModel?.loadDevices(this)
//            //mDeviceViewModel?.getBoardIpAddress(this)
//            //prefeernce?.savePreferences(AppConstant.SHARED_KEY_LINKING_PROCESS,true)
//
//            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
//            lastClick = SystemClock.elapsedRealtime()
//        }
    }

    fun turnOnBLERequest(){
        mBLEViewModel?.turnOnBLE()
        gotoBleListingScreen()
    }

    fun gotoBleListingScreen(){
        mDisplayNotifications?.fetchData(this)
        Handler(Looper.getMainLooper()).postDelayed({
            mDisplayNotifications?.dismissDialog()
            intent = Intent(this, BleListingActivity::class.java)
            startActivity(intent)
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
        }, 2000)
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main2, menu)//Menu Resource, Menu
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_info -> {
                startActivity(Intent(this, InfoActivity::class.java))
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
        //return true
    }

    override fun onBackPressed() {
        super.onBackPressed()
        mDeviceViewModel?.removeHandlerWiFiRequest()
        mDeviceViewModel?.stopSocket()
        mDisplayNotifications?.dismissDialog()
        finish()
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
    }

    override fun onDestroy() {
        super.onDestroy()
        mDeviceViewModel?.removeHandlerWiFiRequest()
        mDeviceViewModel?.stopSocket()
        mDisplayNotifications?.dismissDialog()
    }

}
