/*
 * Copyright (c) 2010-2020 Belledonne Communications SARL.
 *
 * This file is part of linphone-android
 * (see https://www.linphone.org).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.linphone.activities.main.sidemenu.fragments

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Parcelable
import android.provider.MediaStore
import android.view.View
import android.view.Window
import android.widget.TextView
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import java.io.File
import kotlinx.coroutines.launch
import org.linphone.LinphoneApplication.Companion.coreContext
import org.linphone.LinphoneApplication.Companion.corePreferences
import org.linphone.R
import org.linphone.activities.*
import org.linphone.activities.assistant.AssistantActivity
import org.linphone.activities.main.settings.SettingListenerStub
import org.linphone.activities.main.sidemenu.viewmodels.SideMenuViewModel
import org.linphone.activities.main.viewmodels.SharedMainViewModel
import org.linphone.activities.main.viewmodels.TabsViewModel
import org.linphone.activities.navigateToAbout
import org.linphone.activities.navigateToAccountSettings
import org.linphone.activities.navigateToRecordings
import org.linphone.activities.navigateToSettings
import org.linphone.core.tools.Log
import org.linphone.databinding.SideMenuFragmentBinding
import org.linphone.utils.*

class SideMenuFragment : GenericFragment<SideMenuFragmentBinding>() {
    private lateinit var viewModel: SideMenuViewModel
    private lateinit var sharedViewModel: SharedMainViewModel
    private lateinit var tabviewmodel: TabsViewModel
    private var temporaryPicturePath: File? = null
    lateinit var sm: SessionManager

    override fun getLayoutId(): Int = R.layout.side_menu_fragment

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.lifecycleOwner = this
        sm = SessionManager(this.requireContext())

        viewModel = ViewModelProvider(this).get(SideMenuViewModel::class.java)
        binding.viewModel = viewModel

        sharedViewModel = requireActivity().run {
            ViewModelProvider(this).get(SharedMainViewModel::class.java)
        }

        tabviewmodel = requireActivity().run {
            ViewModelProvider(this).get(TabsViewModel::class.java)
        }

        sharedViewModel.accountRemoved.observe(viewLifecycleOwner, {
            Log.i("[Side Menu] Account removed, update accounts list")
            viewModel.updateAccountsList()
        })

        viewModel.accountsSettingsListener = object : SettingListenerStub() {
            override fun onAccountClicked(identity: String) {
                val args = Bundle()
                args.putString("Identity", identity)
                Log.i("[Side Menu] Navigation to settings for account with identity: $identity")

                sharedViewModel.toggleDrawerEvent.value = Event(true)
                navigateToAccountSettings(identity)
            }
        }

        binding.setSelfPictureClickListener {
            pickFile()
        }

        binding.setAssistantClickListener {
            sharedViewModel.toggleDrawerEvent.value = Event(true)
            startActivity(Intent(context, AssistantActivity::class.java))

            if (corePreferences.enableAnimations) {
                requireActivity().overridePendingTransition(R.anim.enter_right, R.anim.exit_left)
            }
        }

        binding.setSettingsClickListener {
            sharedViewModel.toggleDrawerEvent.value = Event(true)
            navigateToSettings()
        }

        binding.setRecordingsClickListener {
            sharedViewModel.toggleDrawerEvent.value = Event(true)
            navigateToRecordings()
        }

        binding.setAboutClickListener {
            sharedViewModel.toggleDrawerEvent.value = Event(true)
            navigateToAbout()
        }

        binding.setQuitClickListener {
            /*requireActivity().finishAndRemoveTask()
            coreContext.stop()*/
           showDialog()
        }

        binding.setHomeClickListener {

            tabviewmodel.homeselecd.value = true
            sharedViewModel.toggleDrawerEvent.value = Event(true)
            navigateToHome()
        }
       binding.setPbxClickListener {
           sharedViewModel.toggleDrawerEvent.value = Event(true)
           navigateToPbx()
       }
        binding.setLocationProfilesClickListener {
            sharedViewModel.toggleDrawerEvent.value = Event(true)
            navigateToLocaionProfile()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            lifecycleScope.launch {
                val contactImageFilePath = ImageUtils.getFilePathFromPickerIntent(data, temporaryPicturePath)
                if (contactImageFilePath != null) {
                    viewModel.setPictureFromPath(contactImageFilePath)
                }
            }
        }
    }

    private fun pickFile() {
        val cameraIntents = ArrayList<Intent>()

        // Handles image picking
        val galleryIntent = Intent(Intent.ACTION_PICK)
        galleryIntent.type = "image/*"

        if (PermissionHelper.get().hasCameraPermission()) {
            // Allows to capture directly from the camera
            val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            val tempFileName = System.currentTimeMillis().toString() + ".jpeg"
            val file = FileUtils.getFileStoragePath(tempFileName)
            temporaryPicturePath = file
            val publicUri = FileProvider.getUriForFile(
                requireContext(),
                requireContext().getString(R.string.file_provider),
                file
            )
       /*     val publicUri = FileProvider.getUriForFile(
                requireContext(),
                BuildConfig.APPLICATION_ID + ".provider",
                file
            )*/
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, publicUri)
            captureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            cameraIntents.add(captureIntent)
        }

        val chooserIntent =
            Intent.createChooser(galleryIntent, getString(R.string.chat_message_pick_file_dialog))
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(arrayOf<Parcelable>()))

        startActivityForResult(chooserIntent, 0)
    }

    internal fun navigateToDialer() {
        when (findNavController().currentDestination?.id) {
            R.id.masterCallLogsFragment -> findNavController().navigate(
                R.id.action_masterCallLogsFragment_to_dialerFragment,
                null,
                getRightBottomToLeftTopAnimationNavOptions()
            )
            R.id.masterContactsFragment -> findNavController().navigate(
                R.id.action_masterContactsFragment_to_dialerFragment,
                null,
                getRightBottomToLeftTopAnimationNavOptions()
            )
            R.id.masterChatRoomsFragment -> findNavController().navigate(
                R.id.action_masterChatRoomsFragment_to_dialerFragment,
                null,
                getLeftTopToRightBottomAnimationNavOptions()
            )
        }
    }

    private fun showDialog() {
        val dialog = Dialog(this.requireContext())
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.setCancelable(false)
        dialog.setContentView(R.layout.show_logout_popup)
        val body = dialog.findViewById(R.id.header_title_tv) as TextView
        val yesBtn = dialog.findViewById(R.id.logout_okay_tv) as TextView
        val noBtn = dialog.findViewById(R.id.logout_no_tv) as TextView
        yesBtn.setOnClickListener {
            deleteAccount()
            sm.logoutUser()
            dialog.dismiss()
        }
        noBtn.setOnClickListener { dialog.dismiss() }
        dialog.show()
    }

    fun deleteAccount() {

        android.util.Log.e("tag", "deleteAccount: ")
        if (coreContext.core.accountList.size> 0) {

            for (account in coreContext.core.accountList) {
                val authInfo = account.findAuthInfo()
                if (authInfo != null) {
                    Log.i("[Account Settings] Found auth info $authInfo, removing it.")
                    coreContext.core.removeAuthInfo(authInfo)
                } else {
                    Log.w("[Account Settings] Couldn't find matching auth info...")
                }

                coreContext.core.removeAccount(account)
            }
            navigate2login()
        } else {
            navigate2login()
        }
    }

    fun navigate2login() {

        corePreferences.firstStart = true
        sharedViewModel.toggleDrawerEvent.value = Event(true)
        startActivity(Intent(context, AssistantActivity::class.java))

        if (corePreferences.enableAnimations) {
            requireActivity().overridePendingTransition(R.anim.enter_right, R.anim.exit_left)
        }
    }
}
