package com.sunny.app.soft.timberkeyboardnew.ui.fragment

import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.view.View
import com.sunny.app.soft.timberkeyboardnew.App
import com.sunny.app.soft.timberkeyboardnew.R
import com.sunny.app.soft.timberkeyboardnew.databinding.FragmentSettingBinding
import com.sunny.app.soft.timberkeyboardnew.ui.activity.PrivacyActivity

class SettingFragment : BaseFragment(), View.OnClickListener {

    private lateinit var binding: FragmentSettingBinding
    override fun setRootView(): View {
        binding = FragmentSettingBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        binding.settingLayoutRating.setOnClickListener(this)
        binding.settingLayoutShare.setOnClickListener(this)
        binding.layoutPrivacy.setOnClickListener(this)
        val appVersionName = getAppVersionName()

        appVersionName?.let {
            binding.tvVersion.text = String.format(getString(R.string.version), it.versionName)
        }.run {
            binding.tvVersion.text = String.format(getString(R.string.version), "1.0.5")
        }

    }

    override fun onClick(v: View?) {
        when (v) {
            binding.settingLayoutRating -> {
                val url = getString(R.string.link) + App.appContext.packageName
                val intent = Intent(Intent.ACTION_VIEW)
                intent.setData(Uri.parse(url))
                startActivity(intent)
            }

            binding.settingLayoutShare -> {
                val url = getString(R.string.link) + App.appContext.packageName
                val intent = Intent(Intent.ACTION_SEND)
                intent.setType("text/plain")
                intent.putExtra(Intent.EXTRA_TEXT, url)
                startActivity(intent)
            }

            binding.layoutPrivacy -> {
                startActivity(Intent(requireActivity(), PrivacyActivity::class.java))
            }


        }
    }

    private fun getAppVersionName(): PackageInfo? {
        return try {
            requireActivity().packageManager.getPackageInfo(requireActivity().packageName, 0)
        } catch (exception: PackageManager.NameNotFoundException) {
            null
        }
    }
}