@file:Suppress("SENSELESS_COMPARISON")

package com.nivesh.production.partnerOnBoarding.ui.fragments

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.provider.OpenableColumns
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Base64
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.google.android.material.textfield.MaterialAutoCompleteTextView
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.nivesh.production.partnerOnBoarding.BuildConfig
import com.nivesh.production.partnerOnBoarding.R
import com.nivesh.production.partnerOnBoarding.api.ApiClient
import com.nivesh.production.partnerOnBoarding.databinding.FragmentGetStartedBinding
import com.nivesh.production.partnerOnBoarding.db.PreferenceManager
import com.nivesh.production.partnerOnBoarding.model.DataX
import com.nivesh.production.partnerOnBoarding.model.ImageSelectedModel
import com.nivesh.production.partnerOnBoarding.model.request.PartnerRequest
import com.nivesh.production.partnerOnBoarding.model.response.*
import com.nivesh.production.partnerOnBoarding.providerfactory.OnBoardingModelProviderFactory
import com.nivesh.production.partnerOnBoarding.repositories.MainRepository
import com.nivesh.production.partnerOnBoarding.ui.activities.BaseActivity
import com.nivesh.production.partnerOnBoarding.ui.activities.SignUpActivity
import com.nivesh.production.partnerOnBoarding.util.*
import com.nivesh.production.partnerOnBoarding.util.Common.Companion.getDateFromTimeMills
import com.nivesh.production.partnerOnBoarding.util.Common.Companion.getFileExtension
import com.nivesh.production.partnerOnBoarding.util.Common.Companion.isValidIndividualPan
import com.nivesh.production.partnerOnBoarding.util.Common.Companion.showDialogValidation
import com.nivesh.production.partnerOnBoarding.util.Common.Companion.showDialogWithTwoButtons
import com.nivesh.production.partnerOnBoarding.util.Constants.Companion.maxFileSize
import com.nivesh.production.partnerOnBoarding.viewModels.OnBoardingViewModel
import com.squareup.picasso.Picasso
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.*
import java.util.*

class GetStartedFragment : BaseFragment() {
    private var _binding: FragmentGetStartedBinding? = null
    private val binding get() = _binding!!
    private var latestTmpUri: Uri? = null
    private var takeImageResult: ActivityResultLauncher<Uri>? = null
    private var selectImageIntent: ActivityResultLauncher<String>? = null
    private var bitmap: Bitmap? = null
    private var isPanVerify: Boolean = false
    private val mainPANUpload: Int = 1
    private val mainARNPhotoUpload: Int = 2
    private val mainEUINPhotoUpload: Int = 3
    private var actionType: Int = -1

    private var panString: String = ""
    private var panFileExt: String? = ""
    private var docValue: String = ""
    private var isFront: Boolean = false
    private var isBack: Boolean = false
    private var isARN: Boolean = false
    private var isEUIN: Boolean = false
    private lateinit var viewModel: OnBoardingViewModel
    private var listOfDocType: List<Data> = emptyList()
    private var listOfFullDocType: List<Data> = emptyList()
    private var imageSelectedList = ArrayList<ImageSelectedModel>()
    private var imageSelectedArnEuinList = ArrayList<ImageSelectedModel>()
    private var arnList = ArrayList<DataX>()
    private var arnData: DataX? = null
    private lateinit var panRes: PANResponse
    private var selectedDocPosition = -1
    private var documentUrlSelected: String = ""
    private var documentTypeSelected: String = ""
    private var isDataUpdate: Boolean = false
    private val pt = PartnerRequest()
    private var frontUpdatedFileId = 0
    private var backUpdatedFileId = 0
    private var arnUpdatedFileId = 0
    private var euinUpdatedFileId = 0

    private val permissions = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    private val requestCameraPermission = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            takeImage()
        } else {
            showDialogWithTwoButtons(
                (activity as SignUpActivity), getString(R.string.cameraPermission), getString(
                    R.string.permissionRequired
                )
            )
        }
    }

    private val requestGalleryPermission = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) {
        selectImageIntent?.launch("image/*")
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentGetStartedBinding.inflate(inflater, container, false)
        return binding.root
    }

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

    private fun uriToBitmap(selectedFileUri: Uri): Bitmap? {
        try {
            val parcelFileDescriptor =
                requireActivity().contentResolver.openFileDescriptor(selectedFileUri, "r")
            val fileDescriptor: FileDescriptor = parcelFileDescriptor!!.fileDescriptor
            val image = BitmapFactory.decodeFileDescriptor(fileDescriptor)
            parcelFileDescriptor.close()
            return image
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }

    @SuppressLint("SuspiciousIndentation")
    private fun init() {
        viewModel = ViewModelProvider(
            (activity as SignUpActivity),
            OnBoardingModelProviderFactory(MainRepository(ApiClient.getApiClientOne))
        )[OnBoardingViewModel::class.java]

        var docType = "I"
        if (arguments?.getString("arnType").equals(getString(R.string.associateText), true)) {
            commonMethodForVisibility(View.GONE)
            docType = "N"
        } else if (arguments?.getString("arnType").equals(getString(R.string.advisory), true)) {
            commonMethodForVisibility(View.VISIBLE)
            docType = "I"
        }

        documentTypeFullAPI()
        documentTypeAPI(docType)

        binding.edtPassingAMFI.setOnClickListener {
            Common.datePicker(activity as SignUpActivity, binding.edtPassingAMFI, false)
        }

        binding.edtExpiryAMFI.setOnClickListener {
            Common.datePicker(activity as SignUpActivity, binding.edtExpiryAMFI, true)
        }

        selectImageIntent = registerForActivityResult(ActivityResultContracts.GetContent())
        { uri: Uri? ->
            if (uri != null) {
                bitmap = uriToBitmap(uri)
                uploadDocument(uri, "g")
            }
        }

        binding.edtArnNumber.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                Common.removeError(binding.tlArnNumber)
                if (s?.length!! == 7) {
                    apiAMFIDetail("ARN", s.toString())
                }
            }

            override fun afterTextChanged(s: Editable?) {}
        })

        binding.edtEUINNumber.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                Common.removeError(binding.tlEUINNumber)
            }

            override fun afterTextChanged(s: Editable?) {}
        })

        binding.edtEUINNumberNF.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                Common.removeError(binding.tlEUINNumberNF)
            }

            override fun afterTextChanged(s: Editable?) {}
        })

        binding.ivInfo.setOnClickListener {
            addFragment(
                activity as BaseActivity,
                R.id.signUpContainer,
                QuestionsFragment(),
                "GET STARTED",
                true
            )
        }

        binding.edtArnNumber.setOnItemClickListener { _, _, position, _ ->
            if (arnList != null && arnList.size > 0) {
                arnData = arnList[position]
                if (arnData?.EUIN != null)
                    binding.edtEUINNumber.setText(arnData?.EUIN)

                if (arnData?.ARNValidFrom != null)
                    binding.edtPassingAMFI.setText(arnData?.ARNValidFrom)

                if (arnData?.ARNValidTill != null)
                    binding.edtExpiryAMFI.setText(arnData?.ARNValidTill)
            } else {
                binding.edtEUINNumber.setText("")
                binding.edtPassingAMFI.setText("")
                binding.edtExpiryAMFI.setText("")
            }
        }

        takeImageResult =
            registerForActivityResult(ActivityResultContracts.TakePicture()) { isSuccess ->
                if (isSuccess) {
                    latestTmpUri?.let { uri ->
                        uploadDocument(uri, "c")
                    }
                }
            }

        binding.saveDraft.setOnClickListener {
            val partnerRequest = PartnerRequest()

            if (!TextUtils.isEmpty(binding.edtArnNumber.text.toString().trim())) {
                partnerRequest.ARNNumber = binding.edtArnNumber.text.toString().trim()
            }
            if (binding.tlEUINNumber.isVisible && !TextUtils.isEmpty(
                    binding.edtEUINNumber.text.toString().trim()
                )
            ) {
                partnerRequest.EUINNumber = binding.edtEUINNumber.text.toString().trim()
            }
            if (binding.tlEUINNumberNF.isVisible && !TextUtils.isEmpty(
                    binding.edtEUINNumberNF.text.toString().trim()
                )
            ) {
                partnerRequest.EUINNumber = binding.edtEUINNumberNF.text.toString().trim()
            }
            if (!TextUtils.isEmpty(binding.edtPassingAMFI.text.toString().trim())) {
                partnerRequest.DateOfPassingAMFICertificate =
                    binding.edtPassingAMFI.text.toString().trim()
            }
            if (!TextUtils.isEmpty(binding.edtExpiryAMFI.text.toString().trim())) {
                partnerRequest.DateOfExpiryAMFICertificate =
                    binding.edtExpiryAMFI.text.toString().trim()
            }
            if (!TextUtils.isEmpty(binding.edtPanNumber.text.toString().trim())) {
                partnerRequest.PAN = binding.edtPanNumber.text.toString().trim()
            }
            if (!TextUtils.isEmpty(binding.edtFullNamePanCard.text.toString().trim())) {
                partnerRequest.Name = binding.edtFullNamePanCard.text.toString().trim()
            }

            partnerRequest.Mobile = arguments?.getString("mobile")!!
            partnerRequest.PartnerCode =
                PreferenceManager((activity as SignUpActivity)).getPartnerCode()
            partnerRequest.PartnerType = getString(R.string.advisory)
            partnerRequest.DateOfIncorporation =
                getDateFromTimeMills(System.currentTimeMillis())
            apiPartnerCreation(partnerRequest)
        }

        binding.btnNext.setOnClickListener {
            apiUploadDocument()
            if (arguments?.getString("arnType").equals(getString(R.string.associateText), false)) {
                if (validationAssociate()) {
                    val pt = PartnerRequest()
                    pt.Name = binding.edtFullNamePanCard.text.toString()
                    pt.PAN = binding.edtPanNumber.text.toString()

                    val fragment = AlmostThereFragment()
                    val bundle = Bundle()
                    bundle.putSerializable("InputValue", pt)
                    if (arnData != null)
                        bundle.putSerializable("arnData", arnData)
                    bundle.putSerializable("panData", panRes)
                    bundle.putString("mobile", arguments?.getString("mobile"))
                    bundle.putString("arnType", arguments?.getString("arnType"))
                    fragment.arguments = bundle

                    addFragment(
                        activity as BaseActivity,
                        R.id.signUpContainer,
                        fragment,
                        "GET STARTED",
                        true
                    )
                }

            } else if (arguments?.getString("arnType")
                    .equals(getString(R.string.advisory), false)
            ) {
                if (validationAdvisory()) {

                    pt.ARNNumber = binding.edtArnNumber.text.toString()

                    if (binding.edtEUINNumber.visibility == View.VISIBLE)
                        pt.EUINNumber = binding.edtEUINNumber.text.toString()
                    else pt.EUINNumber = binding.edtEUINNumberNF.text.toString()

                    pt.DateOfExpiryAMFICertificate = binding.edtExpiryAMFI.text.toString()
                    pt.Name = binding.edtFullNamePanCard.text.toString()
                    pt.PAN = binding.edtPanNumber.text.toString()
                    pt.DateOfPassingAMFICertificate = binding.edtPassingAMFI.text.toString()
                    pt.PartnerType = arguments?.getString("arnType").toString()
                    pt.PartnerCode =
                        PreferenceManager((activity as SignUpActivity)).getPartnerCode()
                    pt.Mobile = arguments?.getString("mobile").toString()
                    pt.DateOfIncorporation = getDateFromTimeMills(System.currentTimeMillis())

                    apiPartnerCreationContinue(pt)
                }
            }
        }

        binding.uploadFront.setOnClickListener {
            actionType = mainPANUpload
            setImageUploadType(front = true, back = false, aRN = false, eUIN = false)
            if (docValue.isNotBlank() && docValue.isNotEmpty()) {
                selectImage()
            } else {
                showDialogValidation(
                    activity as SignUpActivity,
                    resources.getString(R.string.selectAddressProof)
                )
            }
        }

        binding.mbUploadChangeFront.setOnClickListener {
            actionType = mainPANUpload
            setImageUploadType(front = true, back = false, aRN = false, eUIN = false)
            if (docValue.isNotBlank() && docValue.isNotEmpty()) {
                selectImage()
            } else if (binding.ivFront.drawable != null) {
                selectImage()
            } else {
                showDialogValidation(
                    activity as SignUpActivity,
                    resources.getString(R.string.selectAddressProof)
                )
            }
        }

        binding.mbUploadChangeBack.setOnClickListener {
            actionType = mainPANUpload
            setImageUploadType(front = false, back = true, aRN = false, eUIN = false)
            if (docValue.isNotBlank() && docValue.isNotEmpty()) {
                selectImage()
            } else if (binding.ivBack.drawable != null) {
                selectImage()
            } else {
                showDialogValidation(
                    activity as SignUpActivity,
                    resources.getString(R.string.selectAddressProof)
                )
            }
        }

        binding.uploadBack.setOnClickListener {
            actionType = mainPANUpload
            setImageUploadType(front = false, back = true, aRN = false, eUIN = false)
            if (docValue.isNotBlank() && docValue.isNotEmpty()) {
                selectImage()
            } else {
                showDialogValidation(
                    activity as SignUpActivity,
                    resources.getString(R.string.selectAddressProof)
                )
            }
        }

        binding.rlARNUpload.setOnClickListener {
            actionType = mainARNPhotoUpload
            setImageUploadType(front = false, back = false, aRN = true, eUIN = false)
            selectImage()
        }

        binding.rlEUINUpload.setOnClickListener {
            actionType = mainEUINPhotoUpload
            setImageUploadType(front = false, back = false, aRN = false, eUIN = true)
            selectImage()
        }

        binding.edtPanNumber.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                Common.removeError(binding.tlPanNumber)

                if (arguments?.getString("arnType").equals(getString(R.string.advisory), true)) {
                    if (!isValidIndividualPan(s.toString().trim())) {
                        binding.rlEUINUpload.visibility = View.GONE
                        binding.edtEUINNumber.visibility = View.VISIBLE
                        binding.tlEUINNumber.visibility = View.VISIBLE
                    } else {
                        binding.rlEUINUpload.visibility = View.VISIBLE
                        if (!TextUtils.isEmpty(binding.edtEUINNumber.text)) {
                            binding.edtEUINNumberNF.setText(binding.edtEUINNumber.text.toString())
                            binding.edtEUINNumber.visibility = View.GONE
                            binding.tlEUINNumber.visibility = View.GONE
                        }
                    }
                }

                if (s.toString().trim().length >= 10 && !isPanVerify) {
                    apiPANVerify(s.toString().trim())
                } else if (s.toString().trim().length < 10 && !isPanVerify) {
                    binding.edtPanNumber.setCompoundDrawablesWithIntrinsicBounds(
                        0,
                        0,
                        0,
                        0
                    )
                    binding.edtFullNamePanCard.setText("")
                } else if (s.toString().length < 10) {
                    isPanVerify = false
                    binding.edtPanNumber.setCompoundDrawablesWithIntrinsicBounds(
                        0,
                        0,
                        0,
                        0
                    )
                } else {
                    binding.edtPanNumber.setCompoundDrawablesWithIntrinsicBounds(
                        0,
                        0,
                        R.drawable.svg_pan_verified,
                        0
                    )
                }
            }

            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
        })

        binding.spDocType.onItemClickListener =
            AdapterView.OnItemClickListener { parent, _, position, _ ->
                val getCodes: Data = parent.getItemAtPosition(position) as Data
                imageSelectedList.clear()
                docValue = getCodes.DocumentType
                selectedDocPosition = position
                setVisibility(listOfDocType[position].DocumentType)
            }

        (activity as SignUpActivity).viewModelOne.getPANDetailMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            showProgress(View.GONE)
            val res: PANResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    PANResponse::class.java
                )

            panRes = res
            isPanVerify = if (res.Status == "success") {
                binding.edtPanNumber.setCompoundDrawablesWithIntrinsicBounds(
                    0,
                    0,
                    R.drawable.svg_pan_verified,
                    0
                )
                binding.edtFullNamePanCard.setText(res.Result.data.FullName)
                true
            } else {
                commonErrorMethod(
                    binding.edtPanNumber,
                    binding.tlPanNumber,
                    getString(R.string.invalidPAN)
                )
            }
        }

        (activity as SignUpActivity).viewModelOne.getPartnerCreationSaveMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            val res: PartnerResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    PartnerResponse::class.java
                )
            Log.e("check_res_partner", res.toString())
            if (res.Status != null) {
                showDialogValidation((activity as SignUpActivity), "Detail Saved in Draft")
            }
        }

        (activity as SignUpActivity).viewModelOne.getPartnerCreationContinueMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            val res: PartnerResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    PartnerResponse::class.java
                )

            if (res.Status != null || res.Status == getString(R.string.successText)) {
                val fragment = AlmostThereFragment()
                val bundle = Bundle()
                bundle.putSerializable("InputValue", pt)
                bundle.putSerializable("arnData", arnData)
                bundle.putSerializable("panData", panRes)
                bundle.putString("mobile", arguments?.getString("mobile"))
                bundle.putString("arnType", arguments?.getString("arnType"))
                fragment.arguments = bundle

                addFragment(
                    activity as BaseActivity,
                    R.id.signUpContainer,
                    fragment,
                    "GET STARTED",
                    true
                )
            }
        }

        (activity as SignUpActivity).viewModelOne.getDocumentTypeFullMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            val res: DocumentTypeResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    DocumentTypeResponse::class.java
                )

            if (res.Status == getString(R.string.successText)) {
                listOfFullDocType = res.Result.Data
            }
        }

        (activity as SignUpActivity).viewModelOne.getDocumentTypeMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            ProgressUtil.hideLoading()
            val res: DocumentTypeResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    DocumentTypeResponse::class.java
                )
            Log.e("checkDocRes", res.toString())
            if (res.Status == getString(R.string.successText)) {
                listOfDocType = res.Result.Data
                if (listOfDocType.isNotEmpty()) {
                    setUpDocAdapter(listOfDocType)

                    if (arguments?.containsKey("partnerResponse") == true) {
                        val partnerDetailResponse: PartnerDetailResponse? =
                            (arguments?.getSerializable("partnerResponse") as? PartnerDetailResponse)
                        setUpPartnerResponseData(partnerDetailResponse)
                    }
                }
                apiAMFIDetail("Mobile", arguments?.getString("mobile"))
            }
        }

        (activity as SignUpActivity).viewModelOne.getDocumentUploadMutableData.observe(
            viewLifecycleOwner
        ) { response ->
            val res: DocumentUploadResponse =
                Gson().fromJson(
                    response?.data.toString(),
                    DocumentUploadResponse::class.java
                )

            if (res.Status == getString(R.string.successText)) {
                Toast.makeText(activity as SignUpActivity, res.Message, Toast.LENGTH_LONG)
                    .show()
            }
        }
    }

    private fun setImageUploadType(front: Boolean, back: Boolean, aRN: Boolean, eUIN: Boolean) {
        isFront = front
        isBack = back
        isARN = aRN
        isEUIN = eUIN
    }

    private fun setUpPartnerResponseData(partnerResponse: PartnerDetailResponse?) {
        if (partnerResponse?.Result?.ARNNumber != null) {
            binding.edtArnNumber.setText(partnerResponse.Result.ARNNumber)
        }

        if (partnerResponse?.Result?.EUINNumber != null) {
            binding.edtEUINNumber.setText(partnerResponse.Result.EUINNumber)
        }

        if (partnerResponse?.Result?.DateOfPassingAMFICertificate != null) {
            binding.edtPassingAMFI.setText(partnerResponse.Result.DateOfPassingAMFICertificate)
        }

        if (partnerResponse?.Result?.DateOfExpiryAMFICertificate != null) {
            binding.edtExpiryAMFI.setText(partnerResponse.Result.DateOfExpiryAMFICertificate)
        }

        if (partnerResponse?.Result?.PAN != null) {
            binding.edtPanNumber.setText(partnerResponse.Result.PAN)
        }

        if (partnerResponse?.Result?.Name != null) {
            binding.edtFullNamePanCard.setText(partnerResponse.Result.Name)
        }

        if (partnerResponse?.Result?.filedetails != null && partnerResponse.Result.filedetails.isNotEmpty()) {
            if (listOfFullDocType != null && listOfFullDocType.isNotEmpty()) {
                for (i in listOfFullDocType.indices) {
                    for (j in partnerResponse.Result.filedetails.indices) {
                        if (listOfFullDocType[i].DocumentId == partnerResponse.Result.filedetails[j].DocumentId) {
                            for(k in listOfDocType.indices) {
                                if(listOfFullDocType[i].DocumentType == listOfDocType[k].DocumentType) {
                                    binding.spDocType.setText(listOfDocType[k].DocumentType)
                                    setUpDocAdapter(listOfDocType)
                                }
                            }
                            if (partnerResponse.Result.filedetails[j].FilePath != null) {
                                isDataUpdate = true
                                documentUrlSelected = partnerResponse.Result.filedetails[j].FilePath
                                documentTypeSelected = listOfFullDocType[i].DocumentType
                                setVisibilityUrl(documentTypeSelected)
                                setFrontHideVisibleUrl(j, documentUrlSelected,partnerResponse.Result.filedetails[j].DocumentId,
                                partnerResponse.Result.filedetails[j].FileId)
                            }
                        }
                    }
                }
            }
        }
    }

    private fun setUpDocAdapter(listOfDocType: List<Data>) {
        val adapter = ArrayAdapter(
            activity as SignUpActivity,
            android.R.layout.simple_list_item_1,
            listOfDocType
        )
        binding.spDocType.setAdapter(adapter)
    }

    private fun apiPartnerCreation(partnerRequest: PartnerRequest) {
        val data = GsonBuilder().create().toJson(partnerRequest, PartnerRequest::class.java)
        Log.e("partnerCreation", data.toString())
        (activity as SignUpActivity).viewModelOne.getPartnerCreateSaveData(
            partnerRequest,
            "",
            (activity as SignUpActivity)
        )
    }

    private fun apiPartnerCreationContinue(partnerRequest: PartnerRequest) {
        val data = GsonBuilder().create().toJson(partnerRequest, PartnerRequest::class.java)
        Log.e("partnerCreationContinue", data.toString())
        (activity as SignUpActivity).viewModelOne.getPartnerCreateContinueData(
            partnerRequest,
            "",
            (activity as SignUpActivity)
        )
    }

    private fun commonMethodForVisibility(visibility: Int) {
        binding.edtArnNumber.visibility = visibility
        binding.tlArnNumber.visibility = visibility
        binding.edtEUINNumber.visibility = visibility
        binding.tlEUINNumber.visibility = visibility
        binding.tlArnNumber.visibility = visibility
        binding.edtPassingAMFI.visibility = visibility
        binding.tlPassingAMFI.visibility = visibility
        binding.edtExpiryAMFI.visibility = visibility
        binding.tlExpiryAMFI.visibility = visibility
    }

    private fun documentTypeFullAPI() {

        if (listOfDocType != null && listOfDocType.isEmpty()) {
            Log.e("check_activity_name", (activity as SignUpActivity).localClassName)
            (activity as SignUpActivity).viewModelOne.getDocumentTypeFull(
                "3",//Currently it is static
                "",
                (activity as SignUpActivity)
            )
        }
    }

    @SuppressLint("SuspiciousIndentation")
    private fun documentTypeAPI(docType: String) {
        try {
            if (listOfDocType != null && listOfDocType.isEmpty()) {
                ProgressUtil.showLoading(activity as SignUpActivity)
                Log.e("check_activity_name", (activity as SignUpActivity).localClassName)
                (activity as SignUpActivity).viewModelOne.getDocumentType(
                    "3",//Currently it is static
                    docType,
                    (activity as SignUpActivity)
                )
            }

        } catch (e: Exception) {
            Log.e("checkPANError", e.message.toString())
        }
    }

    private fun apiPANVerify(pan: String) {
        try {
            (activity as SignUpActivity).viewModelOne.getPANDetail(
                pan,
                (activity as SignUpActivity)
            )
            showProgress(View.VISIBLE)
        } catch (e: Exception) {
            ProgressUtil.hideLoading()
            Log.e("checkPANError", e.message.toString())
        }
    }

    private fun showProgress(view: Int) {
        binding.rlProgress.visibility = view
    }

    private fun apiAMFIDetail(type: String, value: String?) {
        val jsonObject = JSONObject()
        val mediaType = "application/json; charset=utf-8".toMediaType()
        val body: RequestBody

        try {
            jsonObject.put(type, value)
            body = jsonObject.toString().toRequestBody(mediaType)

            (activity as SignUpActivity).viewModelOne.getAMFIDetail(
                body,
                "",
                (activity as SignUpActivity)
            )

            (activity as SignUpActivity).viewModelOne.getAMFIDetailMutableData.observe(
                viewLifecycleOwner
            ) { response ->
                val res: GetAMFIDetailResponse =
                    Gson().fromJson(
                        response?.data.toString(),
                        GetAMFIDetailResponse::class.java
                    )
                if (res != null && res.Result.data != null) {
                    arnList.clear()
                    arnList = res.Result.data as ArrayList<DataX>

                    if (res.Status == getString(R.string.successText)) {
                        if (type == "ARN") {
                            if (arnList.size > 0) {
                                arnData = arnList[0]
                                if (arnData?.EUIN != null)
                                    binding.edtEUINNumber.setText(arnData?.EUIN)

                                if (arnData?.ARNValidFrom != null)
                                    binding.edtPassingAMFI.setText(arnData?.ARNValidFrom)

                                if (arnData?.ARNValidTill != null)
                                    binding.edtExpiryAMFI.setText(arnData?.ARNValidTill)
                            }

                            setArnUploadVisibility(View.GONE)
                        } else {
                            val adapter = ArrayAdapter(
                                (activity as SignUpActivity),
                                androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,
                                arnList
                            )
                            binding.edtArnNumber.setAdapter(adapter)
                        }
                    } else if (type == "ARN" && binding.edtArnNumber.text.length >= 7) {
                        setArnUploadVisibility(View.VISIBLE)
                    }
                }
            }

        } catch (e: Exception) {
            Log.e("check_error", e.message.toString() + "\n" + type + "\n" + value)
        }
    }

    private fun setArnUploadVisibility(visibility: Int) {
        binding.rlARNUpload.visibility = visibility
    }

    private fun commonErrorMethod(
        inputText: TextInputEditText,
        inputError: TextInputLayout,
        strMessage: String
    ): Boolean {
        inputText.requestFocus()
        inputError.error = strMessage
        return false
    }

    private fun commonErrorMethodAutoComplete(
        inputText: MaterialAutoCompleteTextView,
        inputError: TextInputLayout,
        strMessage: String
    ): Boolean {
        inputText.requestFocus()
        inputError.error = strMessage
        return false
    }

    private fun validationAssociate(): Boolean {
        return if (binding.edtPanNumber.text.toString().isEmpty()) {
            commonErrorMethod(
                binding.edtPanNumber,
                binding.tlPanNumber,
                getString(R.string.pleaseArnNum)
            )
        } else if (binding.edtFullNamePanCard.text.toString().isEmpty()) {
            commonErrorMethod(
                binding.edtFullNamePanCard,
                binding.tlFullNamePanCard,
                getString(R.string.pleaseArnNum)
            )
        } else return true
    }

    private fun validationAdvisory(): Boolean {
        return if (binding.edtArnNumber.text.toString().isEmpty()) {
            commonErrorMethodAutoComplete(
                binding.edtArnNumber,
                binding.tlArnNumber,
                getString(R.string.pleaseArnNum)
            )
        } else if (binding.edtEUINNumber.visibility != View.VISIBLE && binding.edtEUINNumber.text.toString()
                .isEmpty()
        ) {
            commonErrorMethod(
                binding.edtEUINNumber,
                binding.tlEUINNumber,
                getString(R.string.pleaseEuinNum)
            )
        } else if (binding.edtEUINNumberNF.visibility != View.VISIBLE && binding.edtEUINNumberNF.text.toString()
                .isEmpty()
        ) {
            commonErrorMethod(
                binding.edtEUINNumberNF,
                binding.tlEUINNumberNF,
                getString(R.string.pleaseEuinNum)
            )
        } else if (binding.edtPassingAMFI.text.toString().isEmpty()) {
            commonErrorMethod(
                binding.edtPassingAMFI,
                binding.tlPassingAMFI,
                getString(R.string.pleasePassingCertificate)
            )
        } else if (binding.edtExpiryAMFI.text.toString().isEmpty()) {
            commonErrorMethod(
                binding.edtExpiryAMFI,
                binding.tlExpiryAMFI,
                getString(R.string.pleaseExpirCertificate)
            )
        } else if (binding.edtPanNumber.text.toString().isEmpty()) {
            commonErrorMethod(
                binding.edtPanNumber,
                binding.tlPanNumber,
                getString(R.string.emptyPAN)
            )
        } else if (!isPanVerify) {
            commonErrorMethod(
                binding.edtPanNumber,
                binding.tlPanNumber,
                getString(R.string.invalidPAN)
            )
        } else if (binding.edtFullNamePanCard.text.toString().isEmpty()) {
            commonErrorMethod(
                binding.edtFullNamePanCard,
                binding.tlFullNamePanCard,
                getString(R.string.full_name_as_on_pan_card)
            )
        } else if (!isDataUpdate) {
            if (imageSelectedList == null || imageSelectedList.size == 0) {
                showDialogValidation(
                    (activity as SignUpActivity),
                    resources.getString(R.string.selectAddressProof)
                )
                return false
            } else true
        } else if (isDataUpdate) {
            return if (TextUtils.isEmpty(documentTypeSelected) && TextUtils.isEmpty(
                    documentUrlSelected
                )
            ) {
                showDialogValidation(
                    (activity as SignUpActivity),
                    getString(R.string.addressProofType)
                )
                false
            } else {
                true
            }
        } else {
            true
        }
    }

    private fun selectImage() {
        val builder = AlertDialog.Builder(
            activity as SignUpActivity
        )
        builder.setTitle(getString(R.string.addPhoto))
        builder.setItems(
            arrayOf(
                getString(R.string.takePhoto),
                getString(R.string.chooseFromGallery),
                getString(R.string.cancel)
            )
        ) { dialog: DialogInterface, pos ->
            when (pos) {
                0 -> {
                    if (hasPermissions(
                            activity as SignUpActivity,
                            Manifest.permission.CAMERA
                        )
                    ) {
                        takeImage()
                    } else {
                        onClickRequestPermission()
                    }
                    dialog.dismiss()
                }
                1 -> {
                    if (hasPermissions(activity as SignUpActivity, *permissions)) {
                        selectImageIntent?.launch("image/*")
                    } else {
                        requestGalleryPermission.launch(permissions)
                    }
                    dialog.dismiss()
                }
                else -> {
                    dialog.dismiss()
                }
            }
        }
        builder.show()
    }

    private fun onClickRequestPermission() {
        when {
            ContextCompat.checkSelfPermission(
                activity as SignUpActivity,
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED -> {

            }

            ActivityCompat.shouldShowRequestPermissionRationale(
                activity as SignUpActivity,
                Manifest.permission.CAMERA
            ) -> {
                requestCameraPermission.launch(
                    Manifest.permission.CAMERA
                )
            }

            else -> {
                requestCameraPermission.launch(
                    Manifest.permission.CAMERA
                )
            }
        }
    }

    private fun hasPermissions(activity: Activity, vararg permissions: String?): Boolean {
        for (permission in permissions) {
            if (ActivityCompat.checkSelfPermission(
                    activity,
                    permission!!
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }

    private fun setVisibility(s: String) {
        binding.llDoc.visibility = View.VISIBLE
        if (s.contains(getString(R.string.aadhaarText))) {
            binding.txtFront.visibility = View.VISIBLE
            binding.uploadFront.visibility = View.VISIBLE
            binding.txtBack.visibility = View.VISIBLE
            binding.llBack.visibility = View.VISIBLE
        } else {
            binding.txtFront.visibility = View.VISIBLE
            binding.uploadFront.visibility = View.VISIBLE
            binding.txtBack.visibility = View.GONE
            binding.llBack.visibility = View.GONE
        }
    }

    private fun setVisibilityUrl(s: String) {
        binding.llDoc.visibility = View.VISIBLE
        if (s.contains(getString(R.string.aadhaarText))) {
            binding.txtFront.visibility = View.VISIBLE
            binding.txtBack.visibility = View.VISIBLE
            binding.llBack.visibility = View.VISIBLE
        } else {
            binding.txtFront.visibility = View.VISIBLE
            binding.txtBack.visibility = View.GONE
            binding.llBack.visibility = View.GONE
        }
    }

    private fun getTmpFileUri(): Uri {
        val tmpFile =
            File.createTempFile("tmp_image_file", ".png", requireActivity().cacheDir).apply {
                createNewFile()
                deleteOnExit()
            }

        return FileProvider.getUriForFile(
            requireActivity(), BuildConfig.APPLICATION_ID.plus(".provider"), tmpFile
        )
    }

    private fun takeImage() {
        lifecycleScope.launchWhenStarted {
            try {
                getTmpFileUri().let { uri ->
                    latestTmpUri = uri
                    takeImageResult?.launch(uri)
                }
            } catch (e: Exception) {
                Log.e("check_exception", e.message.toString())
            }
        }
    }

    @SuppressLint("Range")
    fun getFileName(uri: Uri): String {
        var result = ""
        if (uri.scheme == "content") {
            val cursor: Cursor =
                requireActivity().contentResolver.query(uri, null, null, null, null)!!
            cursor.use { cursor1 ->
                if (cursor1.moveToFirst()) {
                    result = cursor1.getString(cursor1.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                }
            }
        }
        if (result.isEmpty()) {
            result = uri.path!!
            val cut = result.lastIndexOf('/')
            if (cut != -1) {
                result = result.substring(cut + 1)
            }
        }
        return result
    }

    @Throws(IOException::class)
    private fun loadFile(file: File): ByteArray {
        val inputStream: InputStream = FileInputStream(file)
        val length = file.length()
        val bytes = ByteArray(length.toInt())
        var offset = 0
        var numRead = 0
        while (offset < bytes.size && inputStream.read(bytes, offset, bytes.size - offset).also {
                numRead = it
            } >= 0) {
            offset += numRead
        }
        if (offset < bytes.size) {
            throw IOException("Could not completely read file " + file.name)
        }
        inputStream.close()
        return bytes
    }

    private fun encodedPANBase64(fileName: File) {
        panString = try {
            val bytes: ByteArray = loadFile(fileName)
            Base64.encodeToString(bytes, Base64.DEFAULT).trim().replace("\n", "")
                .replace("\\s+", "")
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    private fun uploadDocument(uri: Uri, type: String) {
        when (actionType) {
            mainPANUpload -> {
                val fileDir: File = (activity as SignUpActivity).cacheDir
                val fileExtension = File(fileDir.toString().plus("/").plus(getFileName(uri)))
                panFileExt = getFileExtension(getFileName(uri))
                val size: Double = Common.getFileSizeInMB(fileExtension.length())

                setFrontHideVisible(uri)
                if (size < maxFileSize) {
                    if (type == "c") {
                        encodedPANBase64(fileExtension)
                        if (isFront) imageSelectedList.add(ImageSelectedModel(0, fileExtension))
                        else imageSelectedList.add(ImageSelectedModel(1, fileExtension))
                    } else {
                        val bitmap: Bitmap =
                            MediaStore.Images.Media.getBitmap(context?.contentResolver, uri)

                        var fileName = ""
                        if (isFront) fileName = "FRONT_".plus(System.currentTimeMillis().toString())
                        else if (isBack) fileName =
                            "BACK_".plus(System.currentTimeMillis().toString())

                        val file = File(fileDir, fileName.plus(".png"))
                        val fOut = FileOutputStream(file)
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut)

                        fOut.flush()
                        fOut.close()

                        if (file.exists()) encodedPANBase64(file)
                        if (isFront) imageSelectedList.add(ImageSelectedModel(0, file))
                        else imageSelectedList.add(ImageSelectedModel(1, file))
                        Log.e("check_panString", panString + "\n" + bitmap.toString())
                    }
                } else {
                    panString = ""
                    panFileExt = ""
                    showDialogValidation(activity, getString(R.string.fileSizeCant))
                }
            }
            mainARNPhotoUpload -> {
                val fileDir: File = (activity as SignUpActivity).cacheDir
                val fileExtension = File(fileDir.toString().plus("/").plus(getFileName(uri)))
                panFileExt = getFileExtension(getFileName(uri))
                val size: Double = Common.getFileSizeInMB(fileExtension.length())

                binding.ivARNUpload.setImageURI(uri)

                if (size < maxFileSize) {
                    if (type == "c") {
                        encodedPANBase64(fileExtension)
                        imageSelectedArnEuinList.add(ImageSelectedModel(0, fileExtension))
                        binding.tvUploadARNTitle.visibility = View.GONE
                    } else {
                        val bitmap: Bitmap =
                            MediaStore.Images.Media.getBitmap(context?.contentResolver, uri)

                        val fileName: String = System.currentTimeMillis().toString()

                        val file = File(fileDir, fileName.plus(".png"))
                        val fOut = FileOutputStream(file)
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut)

                        fOut.flush()
                        fOut.close()

                        if (file.exists()) encodedPANBase64(file)
                        imageSelectedArnEuinList.add(ImageSelectedModel(0, file))
                        binding.tvUploadARNTitle.visibility = View.GONE
                    }
                } else {
                    panString = ""
                    panFileExt = ""
                    showDialogValidation(activity, getString(R.string.fileSizeCant))
                }
            }
            mainEUINPhotoUpload -> {
                val fileDir: File = (activity as SignUpActivity).cacheDir
                val fileExtension = File(fileDir.toString().plus("/").plus(getFileName(uri)))
                panFileExt = getFileExtension(getFileName(uri))
                val size: Double = Common.getFileSizeInMB(fileExtension.length())

                binding.ivEUINUpload.setImageURI(uri)

                if (size < maxFileSize) {
                    if (type == "c") {
                        encodedPANBase64(fileExtension)
                        imageSelectedArnEuinList.add(ImageSelectedModel(1, fileExtension))
                        binding.tvUploadEUINTitle.visibility = View.GONE
                    } else {
                        val bitmap: Bitmap =
                            MediaStore.Images.Media.getBitmap(context?.contentResolver, uri)

                        val fileName: String = System.currentTimeMillis().toString()

                        val file = File(fileDir, fileName.plus(".png"))
                        val fOut = FileOutputStream(file)
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut)

                        fOut.flush()
                        fOut.close()

                        if (file.exists()) encodedPANBase64(file)
                        imageSelectedArnEuinList.add(ImageSelectedModel(1, fileExtension))
                        binding.tvUploadEUINTitle.visibility = View.GONE
                    }
                } else {
                    panString = ""
                    panFileExt = ""
                    showDialogValidation(activity, getString(R.string.fileSizeCant))
                }
            }
        }
    }

    private fun apiUploadDocument() {
        if (imageSelectedList != null && imageSelectedList.size != 0) {
            for (i in 0 until imageSelectedList.size) {
                if (imageSelectedList[i].pos == 0) {
                    apiUploadRequest(
                        prepareImagePart(imageSelectedList[i].file, "front"),
                        listOfDocType[selectedDocPosition].DocumentId,frontUpdatedFileId
                    )
                } else if (imageSelectedList[i].pos == 1) {
                    apiUploadRequest(
                        prepareImagePart(imageSelectedList[i].file, "back"),
                        listOfDocType[selectedDocPosition].DocumentId,backUpdatedFileId
                    )
                }
            }
        }

        if (imageSelectedArnEuinList != null) {
            for (i in 0 until imageSelectedArnEuinList.size) {
                if (imageSelectedArnEuinList[i].pos == 0) {
                    for (j in listOfFullDocType.indices) {
                        if (listOfFullDocType[j].DocumentType.contains("ARN", ignoreCase = true)) {
                            apiUploadRequest(
                                prepareImagePart(
                                    imageSelectedArnEuinList[i].file,
                                    "front"
                                ), listOfFullDocType[j].DocumentId,arnUpdatedFileId
                            )
                            break
                        }
                    }
                } else if (imageSelectedArnEuinList[i].pos == 1) {
                    for (element in listOfFullDocType) {
                        if (element.DocumentType.contains("EUIN", ignoreCase = true)) {
                            apiUploadRequest(
                                prepareImagePart(
                                    imageSelectedArnEuinList[i].file,
                                    "front"
                                ), listOfFullDocType[i].DocumentId,euinUpdatedFileId
                            )
                        }
                    }
                }
            }
        }
    }

    private fun apiUploadRequest(imagePart: MultipartBody.Part, documentId: Int,fileId: Int) {
        (activity as SignUpActivity).viewModelOne.getDocumentUpload(
            imagePart,
            PreferenceManager((activity as SignUpActivity)).getPartnerCode().toInt(),
            5,
            documentId,
            fileId,
            (activity as SignUpActivity)
        )
    }

    private fun prepareImagePart(file: File, partName: String): MultipartBody.Part {
        val requestBody: RequestBody =
            file.asRequestBody("application/octet-stream".toMediaTypeOrNull())
        return MultipartBody.Part.createFormData(
            "Files",
            partName,
            requestBody
        )
    }

    private fun setFrontHideVisible(uri: Uri) {
        if (isFront) {
            binding.uploadFront.visibility = View.GONE
            binding.ivFrontLayer.setBackgroundColor(Color.parseColor("#99000000"))
            binding.ivFrontTik.setBackgroundResource(R.drawable.svg_tik)
            binding.mbUploadChangeFront.visibility = View.VISIBLE
            binding.ivFront.setImageURI(uri)
        } else {
            binding.uploadBack.visibility = View.GONE
            binding.ivBackLayer.setBackgroundColor(Color.parseColor("#99000000"))
            binding.ivBackTik.setBackgroundResource(R.drawable.svg_tik)
            binding.mbUploadChangeBack.visibility = View.VISIBLE
            binding.ivBack.setImageURI(uri)
        }
    }

    private fun setFrontHideVisibleUrl(pos: Int, url: String, documentId: Int, fileId: Int) {
        if (pos == 0) {
            binding.uploadFront.visibility = View.GONE
            binding.ivFrontLayer.setBackgroundColor(Color.parseColor("#99000000"))
            binding.ivFrontTik.setBackgroundResource(R.drawable.svg_tik)
            binding.mbUploadChangeFront.visibility = View.VISIBLE
            frontUpdatedFileId = fileId
            Picasso.get().load(url).into(binding.ivFront)
        } else {
            binding.uploadBack.visibility = View.GONE
            binding.ivBackLayer.setBackgroundColor(Color.parseColor("#99000000"))
            binding.ivBackTik.setBackgroundResource(R.drawable.svg_tik)
            binding.mbUploadChangeBack.visibility = View.VISIBLE
            backUpdatedFileId = fileId
            Picasso.get().load(url).into(binding.ivBack)
        }

        for(i in listOfFullDocType.indices){
            if(documentId == listOfFullDocType[i].DocumentId){
                if(listOfFullDocType[i].DocumentType.contains("ARN",ignoreCase = true)){
                    Picasso.get().load(url).into(binding.ivARNUpload)
                    binding.tvUploadARNTitle.visibility = View.GONE
                    arnUpdatedFileId = fileId
                    break
                }else if(listOfFullDocType[i].DocumentType.contains("EUIN",ignoreCase = true)){
                    Picasso.get().load(url).into(binding.ivEUINUpload)
                    binding.tvUploadEUINTitle.visibility = View.GONE
                    euinUpdatedFileId = fileId
                    break
                }
            }
        }
    }
}