Untitled

 avatar
unknown
plain_text
a year ago
82 kB
4
Indexable
package com.app.qualityairsolution.Activities

import android.Manifest
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Typeface
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.pdf.PdfDocument
import android.graphics.pdf.PdfDocument.PageInfo
import android.graphics.pdf.PdfRenderer
import android.net.Uri
import android.os.Build
import android.os.Build.VERSION
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.provider.MediaStore
import android.text.Layout
import android.text.SpannableString
import android.text.Spanned
import android.text.StaticLayout
import android.text.TextPaint
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.text.style.TypefaceSpan
import android.util.Log
import android.view.View
import android.view.Window
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.app.qualityairsolution.Activities.Adapter.ImageAdapter
import com.app.qualityairsolution.Activities.Api.RetrofitClient
import com.app.qualityairsolution.Activities.ModelClass.CreateServiceReportModel
import com.app.qualityairsolution.Activities.ModelClass.DataReport
import com.app.qualityairsolution.Activities.ModelClass.ReportData
import com.app.qualityairsolution.Activities.ModelClass.ServiceReport
import com.app.qualityairsolution.Activities.Utils.ImageAdapterCallback
import com.app.qualityairsolution.Activities.Utils.SignatureView
import com.app.qualityairsolution.R
import com.app.qualityairsolution.databinding.ActivityAttachSingatureScreenBinding
import com.squareup.picasso.Picasso
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.random.Random


class AttachSingatureScreenActivity : AppCompatActivity(), ImageAdapterCallback {
    lateinit var binding: ActivityAttachSingatureScreenBinding

    var type = "";
    var companyname1 = "";
    var address1 = "";
    var email1 = "";
    var email2 = "";
    var email3 = "";
    var email4 = "";
    var reportstatus = "draft";
    var ersign  = ""
    var customersign  = ""
     var pdfBody: MultipartBody.Part? = null


    private val REQUEST_IMAGE_CAPTURE = 1
    private val REQUEST_IMAGE_PICK = 2
    private val PERMISSION_REQUEST_CODE = 100
    private lateinit var adapter: ImageAdapter
    private val imageUriList = mutableListOf<Bitmap>()
    private lateinit var paint: SignatureView
    private val MY_PERMISSIONS_REQUEST_STORAGE_PERMISSIONS = 10
    var custid = "";
    private var file: File? = null
    private var filepdf: File? = null
    private var custfile: File? = null
    private var jpgFile: File? = null
    private var custjpgFile: File? = null
    val imageParts = mutableListOf<MultipartBody.Part>()
    var ersignsaved: Boolean = false
    var custsignsaved: Boolean = false
    lateinit var serviceReport: ServiceReport
//    lateinit var serviceReport1: ReportData
    private var currentPhotoPath: String? = null // Path to store the captured image

    private val imagePaths = mutableListOf<String>()

    private var dateobj: Date? = null
    private var scaledBitmap: Bitmap? = null
    lateinit var bmp: Bitmap
    private val pageHeight = 1900
    private val pageWidth = 1085
    private val MAX_IMAGES = 5
    private var selectedImageCount = 0
    lateinit var  receipt: PdfDocument
    lateinit var handler: Handler


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAttachSingatureScreenBinding.inflate(layoutInflater)
        setContentView(binding.root)

        checkPermissions()
        handler = Handler(Looper.getMainLooper())

        bmp = BitmapFactory.decodeResource(resources, R.drawable.header)

        val screenWidth = resources.displayMetrics.widthPixels
        val scaledHeight = bmp.height * screenWidth / bmp.width


        scaledBitmap = Bitmap.createScaledBitmap(bmp, screenWidth, scaledHeight, false)

        adapter = ImageAdapter(imageUriList, this)
        binding.imagercv.layoutManager = LinearLayoutManager(this)
        binding.imagercv.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)

        binding.imagercv.adapter = adapter

        binding.toolbarinclude.titletext.text = "Attach Signature Photos"
        binding.toolbarinclude.backbtn.setOnClickListener {
            finish()
        }
        serviceReport = (intent.getSerializableExtra("servicereport") as? ServiceReport)!!
//        serviceReport1 = (intent.getSerializableExtra("servicereport1") as? ReportData)!!

//        val imageUrls: List<String> = listOf(serviceReport1.images.toString())
//        Log.d("TAG", "AviGyu=====>>>>123: "+imageUrls)

        custid = intent.getStringExtra("custid").toString()
        companyname1 = intent.getStringExtra("companyname1").toString()
        address1 = intent.getStringExtra("address1").toString()
        email1 = intent.getStringExtra("addemail1").toString()
        email2 = intent.getStringExtra("addemail2").toString()
        email3 = intent.getStringExtra("addemail3").toString()
        email4 = intent.getStringExtra("addemail3").toString()
//        var custsign = serviceReport1.customersignature.toString()
//        var ersign = serviceReport1.qasengineersignature.toString()
//
//        loadImageAndSetToSignatureView(custsign, binding.signatureView)
//        loadImageAndSetToSignatureView(ersign, binding.custsignatureView)







//        createReceipt()

        binding.engineerbox.setOnClickListener {
            binding.engineersignbox.visibility = View.VISIBLE
            binding.engineerbox.visibility = View.GONE

        }
        binding.cancel.setOnClickListener {
            binding.engineersignbox.visibility = View.GONE
            binding.engineerbox.visibility = View.VISIBLE

        }

        binding.clear.setOnClickListener {
            binding.signatureView.clear()
        }
        binding.savebutton.setOnClickListener {
            type = "engineer"
            binding.engineersignbox.visibility = View.VISIBLE
            binding.bottombutton2.visibility = View.VISIBLE
            binding.cancel.visibility = View.INVISIBLE
            binding.viewww.visibility = View.VISIBLE
            binding.bottombutton.visibility = View.GONE
            if (binding.signatureView.getSignatureBitmap()
                    .hasAlpha()
            ) {  // Check if there's any drawing

                binding.signatureView.enableDrawing(false)  // Disable drawing
            } else {
                Toast.makeText(this, "Please draw a signature first", Toast.LENGTH_SHORT).show()
            }


            if (VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                takeScreenshot()

            } else {
                if (isStoragePermisssionGranted()) {
                    takeScreenshot()

                } else {
                    requestStoragePermission()

                }
            }


//            AddSignPhotos()
        }
        binding.ReenterSignEr.setOnClickListener {
            binding.signatureView.clear()
            ersignsaved = false
            binding.engineersignbox.visibility = View.VISIBLE
            binding.bottombutton2.visibility = View.GONE
            binding.cancel.visibility = View.VISIBLE
            binding.viewww.visibility = View.VISIBLE
            binding.bottombutton.visibility = View.VISIBLE
            if (binding.signatureView.getSignatureBitmap()
                    .hasAlpha()
            ) {  // Check if there's any drawing

                binding.signatureView.enableDrawing(true)  // Disable drawing
            } else {
                Toast.makeText(this, "Please draw a signature first", Toast.LENGTH_SHORT).show()
            }

        }
        binding.SaveButtonapi.setOnClickListener {
            if (binding.signatureView.isEmpty()) {
                Toast.makeText(this, "Please Add Your Signature First", Toast.LENGTH_SHORT).show()
            } else if (binding.custsignatureView.isEmpty()) {
                Toast.makeText(this, "Please Add Your Signature First", Toast.LENGTH_SHORT).show()


            } else if (!ersignsaved) {
                Toast.makeText(this, "Please Save Engineer Sign First", Toast.LENGTH_SHORT).show()

            } else if (!custsignsaved) {
                Toast.makeText(this, "Please Save Customer Sign First", Toast.LENGTH_SHORT).show()

            }else if (binding.Customername.text.isEmpty()){
                Toast.makeText(this, "Please Enter Customer Name", Toast.LENGTH_SHORT).show()

            }
            else {
                binding.text.visibility = View.GONE
                createReceipt()
            }
        }


        binding.custbox.setOnClickListener {
            binding.custsignbox.visibility = View.VISIBLE
            binding.custbox.visibility = View.GONE

        }
        binding.custcancel.setOnClickListener {
            binding.custsignbox.visibility = View.GONE
            binding.custbox.visibility = View.VISIBLE

        }
        binding.custclear.setOnClickListener {
            binding.custsignatureView.clear()
        }
        binding.custsavebutton.setOnClickListener {


            type = "Customer"
            binding.custsignbox.visibility = View.VISIBLE
            binding.custbottom.visibility = View.VISIBLE

            binding.ReenterSignCust.visibility = View.VISIBLE
            binding.custcancel.visibility = View.INVISIBLE
            binding.custview.visibility = View.VISIBLE
            binding.custbottombutton.visibility = View.GONE
            if (binding.custsignatureView.getSignatureBitmap()
                    .hasAlpha()
            ) {  // Check if there's any drawing

                binding.custsignatureView.enableDrawing(false)  // Disable drawing
            } else {
                Toast.makeText(this, "Please draw a signature first", Toast.LENGTH_SHORT).show()
            }

            if (VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                custtakeScreenshot()

            } else {
                if (isStoragePermisssionGranted()) {
                    custtakeScreenshot()

                } else {
                    requestStoragePermission()

                }
            }
        }
        binding.ReenterSignCust.setOnClickListener {
            binding.custsignatureView.clear()
            custsignsaved = false
            binding.custsignbox.visibility = View.VISIBLE
            binding.ReenterSignCust.visibility = View.GONE
            binding.custbottom.visibility = View.GONE

            binding.custcancel.visibility = View.VISIBLE
            binding.custview.visibility = View.VISIBLE
            binding.custbottombutton.visibility = View.VISIBLE
            if (binding.custsignatureView.getSignatureBitmap()
                    .hasAlpha()
            ) {  // Check if there's any drawing

                binding.custsignatureView.enableDrawing(true)  // Disable drawing
            } else {
                Toast.makeText(this, "Please draw a signature first", Toast.LENGTH_SHORT).show()
            }


        }
        binding.attachimage.setOnClickListener {

            if (imageUriList.size == 5) {
                Toast.makeText(this, "You can select up to 5 images only", Toast.LENGTH_SHORT)
                    .show()
                binding.attachimage.visibility = View.GONE
                binding.attachimage2.visibility = View.VISIBLE

            } else {
                showSelectImageDialog()
            }


        }
        binding.attachimage2.setOnClickListener {
            if (imageUriList.size == 5) {
                Toast.makeText(this, "You can select up to 5 images only", Toast.LENGTH_SHORT)
                    .show()
            }

        }
        binding.preview.setOnClickListener {
//            createReceipt()
//            GetRepotList()
//            val mIntent Intent(this, AttachSingatureScreenActivity::class.java)
//            startActivity(mIntent)

        }
    }

    fun loadImageAndSetToSignatureView(url: String, signatureView: SignatureView) {
        Picasso.get().load(url).into(object : com.squareup.picasso.Target {
            override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
                bitmap?.let {
                    // Convert Bitmap to BitmapDrawable
                    val drawable = BitmapDrawable(resources, bitmap)

                    // Set the drawable to the SignatureView
                    signatureView.setBackgroundDrawable(drawable)
                }
            }

            override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {
                // Handle failed loading of image
            }

            override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
                // Handle loading progress or placeholder (optional)
            }
        })
    }


    private fun createReceipt() {
        val margin = 0 * resources.displayMetrics.density
        val margin2 = 14 * resources.displayMetrics.density
        dateobj = Date()

         receipt = android.graphics.pdf.PdfDocument()
        val paint = Paint()
        val paintline = Paint()

        val receiptPage1 = PageInfo.Builder(
            pageWidth, pageHeight,
            1
        ).create()
        val page1 = receipt.startPage(receiptPage1)
        val canvas = page1.canvas

        try {
            paint.color = getColor(R.color.primecolor)
            paintline.color = getColor(R.color.primecolor)
            paintline.strokeWidth = 3f
            paint.strokeWidth = 2f
            canvas.drawBitmap(scaledBitmap!!, 0f, 0f, paint)
            // Set up the paint for text
            paint.color = getColor(R.color.black)
            paint.textSize = 45f

            paint.textAlign = Paint.Align.LEFT
            var typeface = ResourcesCompat.getFont(this, R.font.poppins_medium)
            paint.typeface = typeface

            // Calculate the position for the text

            val xPos = margin
            val xPoss = margin2
            val yPos = scaledBitmap!!.height + margin + 70  // Adjust the yPos as needed

            // Draw the text below the image
            val text = "FIELD SERVICE REPORT OF AIR COMPRESSOR"
            canvas.drawText(text, xPoss, yPos, paint)
            val textWidth = paint.measureText(text)
            val lineStartX = xPos
            val lineEndX = xPos + textWidth + 40
            val lineY = yPos + 20


            paint.strokeWidth = 10f
            canvas.drawLine(lineStartX, lineY, lineEndX, lineY, paintline)

//            about thh title
            val Title = Paint()
            Title.color = getColor(R.color.black)
            val typefacee = ResourcesCompat.getFont(this, R.font.poppins_medium)
            Title.typeface = typefacee
            Title.textSize = 26f

//            about company name
            val coname = Paint()
            coname.color = getColor(R.color.black)
            val comoan = ResourcesCompat.getFont(this, R.font.poppins_medium)
            coname.typeface = comoan
            coname.textSize = 24f

//            About the address
            val ADDRESS = TextPaint()
            ADDRESS.color = getColor(R.color.start_sc_grey)
            val aDDRESS = ResourcesCompat.getFont(this, R.font.poppins_regular)
            ADDRESS.typeface = aDDRESS
            ADDRESS.textSize = 22f
            val lineSpacing = 40

            var Compantydetails = "COMPANY DETAILS"
            var ContactPerson = "CONTACT PERSON"
            var Date = "DATE"
            var Emailto = "EMAIL TO"
            var Ername = "ENGINEER NAME"





            val column1X = xPoss
            val column2X = xPoss + 450
            val emails = arrayOf(
                email1,
                email2,
                email3,
                email4

            )


            canvas.drawText(Compantydetails, column1X, lineY + 80, Title)
            canvas.drawText(companyname1, column1X, lineY + 125, coname)
            val address1Text = address1.toString()
            val fullAddressText = "Address: $address1Text"
            val spannableString = SpannableString(fullAddressText)

// Load fonts
            val poppinsMedium = ResourcesCompat.getFont(this@AttachSingatureScreenActivity, R.font.poppins_semibold)
            val anotherFont = ResourcesCompat.getFont(this@AttachSingatureScreenActivity, R.font.poppins_regular) // replace 'another_font' with the actual font file name

// Set color and font for "Address:"
            val blackColor = Color.BLACK
            spannableString.setSpan(
                ForegroundColorSpan(blackColor),
                0,
                8, // Length of "Address:"
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                poppinsMedium?.let { TypefaceSpan(it) },
                0,
                8,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )

// Set color and font for the rest of the address
            val greyColor = getColor(R.color.grey) // replace 'grey' with the actual color resource name
            spannableString.setSpan(
                ForegroundColorSpan(greyColor),
                8,
                fullAddressText.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                anotherFont?.let { TypefaceSpan(it) },
                8,
                fullAddressText.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )

// Set font for the entire address text
            val addressPaint = TextPaint().apply {
                typeface = poppinsMedium
                textSize = 22f
                color = blackColor // Default color, will be overridden by spans
            }

            val maxWidth123 = 540
            val staticLayout213 = StaticLayout.Builder
                .obtain(spannableString, 0, spannableString.length, addressPaint, maxWidth123)
                .setAlignment(Layout.Alignment.ALIGN_NORMAL)
                .setIncludePad(false)
                .build()

            canvas.save()
            canvas.translate(column1X, lineY + 130)
            staticLayout213.draw(canvas)
            canvas.restore()

            canvas.drawText(ContactPerson, column2X + 150, lineY + 80, Title)
            canvas.drawText(serviceReport.personName.toString(), column2X + 150, lineY + 120, ADDRESS)




            canvas.drawText(Date, column1X, lineY + 255, Title)
            if (serviceReport.endDate.isEmpty() && serviceReport.endDate.isNullOrBlank()) {
                val dateRange = "${serviceReport.startDate} "
                canvas.drawText(dateRange.toString(), column1X, lineY + 290, ADDRESS)
            } else {
                val dateRange1 = "${serviceReport.startDate} to ${serviceReport.endDate}"
                canvas.drawText(dateRange1.toString(), column1X, lineY + 290, ADDRESS)

            }
            canvas.drawText(Emailto, column2X + 150, lineY + 230, Title)
            for (i in emails.indices) {
                canvas.drawText(
                    emails[i],
                    column2X + 150f,
                    (lineY + 260 + i * lineSpacing).toFloat(),
                    ADDRESS
                )
            }



            canvas.drawText(Ername, column1X, lineY + 340, Title)
            canvas.drawText(serviceReport.engineerName.toString(), column1X, lineY + 375, ADDRESS)


            val lineStartXx = margin2
            val lineEndXx = canvas.width - margin2

            var lineYPosition = (lineY + 415).toInt()

            val paintLine = Paint()
            paintLine.color = getColor(R.color.primeborder)
            paintLine.strokeWidth = 3f

            canvas.drawLine(
                lineStartXx.toFloat(),
                lineYPosition.toFloat(),
                lineEndXx.toFloat(),
                lineYPosition.toFloat(),
                paintLine
            )

//            machine paramteres text is here with margin top


            val topMargin = 45
            val machineparatitle = Paint()
            machineparatitle.color = getColor(R.color.black)
            val machineparatitle1 = ResourcesCompat.getFont(this, R.font.poppins_medium)
            machineparatitle.typeface = machineparatitle1
            machineparatitle.textSize = 34f



            canvas.drawText("MACHINE PARAMETERS", margin2.toFloat(), (lineYPosition + topMargin +20).toFloat(), machineparatitle)
            lineYPosition += 10
            val paintBox1 = Paint().apply { color = getColor(R.color.bgtext) }

            val paintBox2 = Paint().apply { color = getColor(R.color.boxbg1) }

            val paintBox3 = Paint().apply { color = getColor(R.color.boxbg2) }


// Initial positions
            var topPosition = lineYPosition + topMargin + 60
            val boxHeight = 70
            val textYPositionOffset = 45
            val text1 = Paint()
            text1.color = getColor(R.color.black)
            val text11 = ResourcesCompat.getFont(this, R.font.poppins_medium)
            text1.typeface = text11
            text1.textSize = 32f

            val text12 = TextPaint()
            text12.color = getColor(R.color.black)
            val text113 = ResourcesCompat.getFont(this, R.font.poppins_medium)
            text12.typeface = text113
            text12.textSize = 32f

            val text13 = TextPaint()
            text13.color = getColor(R.color.black)
            val text1134 = ResourcesCompat.getFont(this, R.font.poppins_regular)
            text13.typeface = text1134
            text13.textSize = 22f

// Draw the first box and text
            canvas.drawRect(
                margin2.toFloat(),
                topPosition.toFloat(),
                (canvas.width - margin2).toFloat(),
                (topPosition + boxHeight).toFloat(),
                paintBox1
            )
            canvas.drawText(
                "COMPRESSOR MODEL",
                (margin2 + 20).toFloat(),
                (topPosition + textYPositionOffset).toFloat(),
                text1
            )

// Update position for the next box
            topPosition += boxHeight

            val modelname = Paint()
            modelname.color = getColor(R.color.black)
            val modelnamee = ResourcesCompat.getFont(this, R.font.poppins_medium)
            modelname.typeface = modelnamee
            modelname.textSize = 26f


            val cmvlue = Paint()
            cmvlue.color = getColor(R.color.black)
            val cmvlue1 = ResourcesCompat.getFont(this, R.font.poppins_regular)
            cmvlue.typeface = cmvlue1
            cmvlue.textSize = 22f



            canvas.drawRect(
                margin2.toFloat(),
                topPosition.toFloat(),
                (canvas.width - margin2).toFloat(),
                (topPosition + boxHeight).toFloat(),
                paintBox2
            )
            canvas.drawText(
                serviceReport.compressorModel.toString(),

                (margin2 + 20).toFloat(),
                (topPosition + textYPositionOffset).toFloat(),
                modelname
            )

// Update position for the next box
            topPosition += boxHeight

// Draw the third box and text
            canvas.drawRect(
                margin2.toFloat(),
                topPosition.toFloat(),
                (canvas.width - margin2).toFloat(),
                (topPosition + boxHeight).toFloat(),
                paintBox3
            )
            canvas.drawText(
                "SERIAL NO: ${serviceReport.serialNo}",
                (margin2 + 20).toFloat(),
                (topPosition + textYPositionOffset).toFloat(),
                cmvlue
            )

// Update position for the next box
            topPosition += boxHeight

// Draw the fourth box and text
            canvas.drawRect(
                margin2.toFloat(),
                topPosition.toFloat(),
                (canvas.width - margin2).toFloat(),
                (topPosition + boxHeight).toFloat(),
                paintBox2
            )
            val runningHours = serviceReport.runningHour
            val runhr = "RUNNING HOURS: $runningHours Hrs"
            canvas.drawText(
                runhr,
                (margin2 + 20).toFloat(),
                (topPosition + textYPositionOffset).toFloat(),
                cmvlue
            )










            topPosition += boxHeight

            canvas.drawRect(
                margin2.toFloat(),
                topPosition.toFloat(),
                (canvas.width - margin2).toFloat(),
                (topPosition + boxHeight).toFloat(),
                paintBox3
            )
            val loadinghr = serviceReport.loadingHour
            if (serviceReport.loadingHour.isEmpty() && serviceReport.loadingHour.isNullOrBlank()) {
                val loadhr = "LOADING HOUR: "
                canvas.drawText(
                    loadhr,
                    (margin2 + 20).toFloat(),
                    (topPosition + textYPositionOffset).toFloat(),
                    cmvlue
                )

            } else {
                val loadhr1 = "LOADING HOUR: $loadinghr Hrs"
                canvas.drawText(
                    loadhr1,
                    (margin2 + 20).toFloat(),
                    (topPosition + textYPositionOffset).toFloat(),
                    cmvlue
                )
            }


            topPosition += boxHeight + 30


            // Define paint for nature of complaint and observation
            val complaintPaint = TextPaint().apply {
                color = getColor(R.color.black)
                typeface = ResourcesCompat.getFont(this@AttachSingatureScreenActivity, R.font.poppins_regular)
                textSize = 26f
            }

// Draw "NATURE OF COMPLAINT" title
            canvas.drawText(
                "NATURE OF COMPLAINT",
                (margin2 + 0).toFloat(),
                (topPosition + textYPositionOffset).toFloat(),
                text12
            )

            topPosition += boxHeight - 50

// Draw complaint text
            val complaintText = serviceReport.complaint.toString()
            val maxWidth = 970
            val complaintStaticLayout = StaticLayout.Builder
                .obtain(complaintText, 0, complaintText.length, ADDRESS, maxWidth)
                .setAlignment(Layout.Alignment.ALIGN_NORMAL)
                .setLineSpacing(0f, 1.0f)
                .setIncludePad(false)
                .build()

            canvas.save()
            canvas.translate(
                (margin2 + 0).toFloat(),
                (topPosition + textYPositionOffset).toFloat()
            )
            complaintStaticLayout.draw(canvas)
            canvas.restore()

            topPosition += complaintStaticLayout.height + 10 // Adjust the spacing as needed

// Draw separator line
            val linePaint = Paint().apply {
                color = getColor(R.color.primeborder)
                strokeWidth = 3f
            }

            canvas.drawLine(
                margin2.toFloat(), // startX
                (topPosition + textYPositionOffset).toFloat(), // startY
                (canvas.width - margin2).toFloat(), // stopX
                (topPosition + textYPositionOffset).toFloat(), // stopY
                linePaint
            )

            topPosition += 30 // Adjust spacing as needed

// Draw "OBSERVATION" title
            canvas.drawText(
                "OBSERVATION",
                (margin2 + 0).toFloat(),
                (topPosition + textYPositionOffset+20).toFloat(),
                text12
            )

            topPosition += boxHeight - 40

// Format and draw observation text
            val observation1 = serviceReport.observations.toString()
            val lines = observation1.split("\n")
            val formattedText = StringBuilder()
            for (line in lines) {
                if (line.isNotBlank()) {
                    formattedText.append("• ").append(line).append("\n")
                }
            }

            val observationPaint = TextPaint().apply {
                color = getColor(R.color.start_sc_grey)
                typeface = ResourcesCompat.getFont(this@AttachSingatureScreenActivity, R.font.poppins_regular)
                textSize = 26f
            }

            val maxWidthh = 970 // Adjust this value to your desired maximum width
            val observationStaticLayout = StaticLayout.Builder
                .obtain(formattedText.toString(), 0, formattedText.length, observationPaint, maxWidthh)
                .setAlignment(Layout.Alignment.ALIGN_NORMAL)
                .setLineSpacing(0f, 1.2f)
                .setIncludePad(true)
                .build()

            canvas.save()
            canvas.translate((margin2 + 20).toFloat(), (topPosition + textYPositionOffset).toFloat())
            observationStaticLayout.draw(canvas)
            canvas.restore()

            topPosition += observationStaticLayout.height + 10 // Adjust the spacing as needed

// Draw bottom line
            val bottomLineY = topPosition + 60 // Adjust as needed
            canvas.drawLine(
                margin2.toFloat(), // startX
                bottomLineY.toFloat(), // startY
                (canvas.width - margin2).toFloat(), // stopX
                bottomLineY.toFloat(), // stopY
                linePaint
            )
            receipt.finishPage(page1)


//            Second Page Start

            val receiptPage2 = PageInfo.Builder(pageWidth, pageHeight, 2).create()
            val page2 = receipt.startPage(receiptPage2)
            val canvas2 = page2.canvas

            val title = "ACTION TAKEN"
            val apiResponseText = serviceReport.action.toString()

            val topMarginsecnd = convertSdpToPixels(10)
            val xPosPage2 = 50f
            var yPosPage2 = 50f + topMarginsecnd

// Draw title
            canvas2.drawText(title, xPosPage2, yPosPage2, text1)
            yPosPage2 += text1.descent() - text1.ascent()



// Define the maximum width for the text
            val maxWidtha = pageWidth - 2 * xPosPage2

// Create StaticLayout for the entire API response text
            val staticLayouta = StaticLayout.Builder.obtain(apiResponseText, 0, apiResponseText.length, observationPaint, maxWidtha.toInt())
                .setAlignment(Layout.Alignment.ALIGN_NORMAL)
                .setLineSpacing(0f, 1.2f)
                .setIncludePad(true)
                .build()

            canvas2.save()
            canvas2.translate(xPosPage2 + 20, yPosPage2 - 30)
            staticLayouta.draw(canvas2)
            canvas2.restore()

// Calculate the y-position after the "ACTION TAKEN" text
            yPosPage2 += staticLayouta.height + 10 // Add spacing after the text

// Draw a line below the text
            val lineStartXa = xPosPage2
            val lineStopX = xPosPage2 + maxWidtha
            val lineYa = yPosPage2-20  // Add some spacing before the line
            canvas2.drawLine(lineStartXa, lineYa, lineStopX, lineYa, linePaint)
            yPosPage2 = lineYa+30 // Add spacing after the line


//======================================================================================================================
//            AKKI
//            Add Box code
            val topPositionPage2 = yPosPage2
            val boxHeightPage2 = 70
            val textYPositionOffsetPage2 = 45

            canvas2.drawRect(
                xPosPage2,
                topPositionPage2,
                (pageWidth - xPosPage2),
                (topPositionPage2 + boxHeightPage2),
                paintBox1
            )

            val boxText = "MEASUREMENT POINTS"
            canvas2.drawText(
                boxText,
                (xPosPage2 + 20),
                (topPositionPage2 + textYPositionOffsetPage2),
                text1
            )
            // Define the second box properties
            val topPositionPage2SecondBox = topPositionPage2 + boxHeightPage2
            val boxHeightPage2SecondBox = 70
            val textYPositionOffsetPage2SecondBox = 45


            val boxtext = Paint()
            boxtext.color = getColor(R.color.black)
            val boxtexx = ResourcesCompat.getFont(this, R.font.poppins_regular)
            boxtext.typeface = boxtexx
            boxtext.textSize = 20f

            val boxtextunit = Paint()
            boxtextunit.color = getColor(R.color.start_sc_grey)
            val boxtexxunit = ResourcesCompat.getFont(this, R.font.poppins_regular)
            boxtextunit.typeface = boxtexxunit
            boxtextunit.textSize = 20f

// Draw the second box
            canvas2.drawRect(xPosPage2, topPositionPage2SecondBox, (pageWidth - xPosPage2), (topPositionPage2SecondBox + boxHeightPage2SecondBox), paintBox2)

// Text for the second box
            val boxTextSecondBox = "Compressor Outlet Temperature"
            val boxTextNineBox = " Working Pressure"
            val boxTextThirdBox = "Loading Pressure"
            val boxTextUPBox = "Unloading Pressure"
            val boxTextFourthBox ="Oil Pressure"
            val boxTextOThBox ="Oil Temperature"
            val boxTextFifthBox = "DP-Airfilter"
            val boxTextOTEBox = "Outlet Temperature Element 1"
            val boxTextSixthBox = "Inlet Temperature Element 2"
            val boxTextOTE2Box = "Outlet Temperature Element 2"
            val boxTextSeventhBox = "Intercooler 1 Pressure"
            val boxTextCWTBox = "Cool Water In Temperature"
            val boxTextEighthBox = "Cool Water Out Temperature"


            val boxTextSecondBoxx = serviceReport.CompressorOutletTemprature.toString()+" DEG"
            val boxTextNineBoxx = serviceReport.WorkingPressure.toString()+" BAR"
            val boxTextThirdBoxx = serviceReport.LoadingPressure.toString()+" BAR"
            val boxTextTBoxx = serviceReport.UnloadingPressure.toString()+" BAR"
            val boxText4Boxx = serviceReport.OilPressure.toString()+" BAR"
            val boxTextOBoxx =serviceReport.Temprature.toString()+" BAR"
            val boxText5Boxx = serviceReport.DpAirFilter.toString()+" MBA"
            val boxTextasBoxx = serviceReport.firstststageoutlettemprature+" DEG"
            val boxText6Boxx =  serviceReport.secndstageinlettemprature+" DEG"
            val boxTextOTEBoxx =serviceReport.secondOutletTemp+" DEG"
            val boxText7Boxx = serviceReport.intercooler+" BAR"
            val boxTextCWTCBoxx =serviceReport.waterInletTemp+" DEG"
            val boxText8Boxx = serviceReport.waterOutletTemp+" DEG"

            val showSecondBox = !serviceReport.CompressorOutletTemprature.isNullOrEmpty()
            val showThirdBox = !serviceReport.WorkingPressure.isNullOrEmpty()
            val showFourthBox = !serviceReport.LoadingPressure.isNullOrEmpty()
            val showFifthBox = !serviceReport.UnloadingPressure.isNullOrEmpty()
            val showSixthBox = !serviceReport.OilPressure.isNullOrEmpty()
            val showSeventhBox = !serviceReport.Temprature.isNullOrEmpty()
            val showEighthBox = !serviceReport.DpAirFilter.isNullOrEmpty()
            val showNinthBox = !serviceReport.firstststageoutlettemprature.isNullOrEmpty()
            val showTenthBox = !serviceReport.secndstageinlettemprature.isNullOrEmpty()
            val showEleventhBox = !serviceReport.secondOutletTemp.isNullOrEmpty()
            val showTwelvethBox = !serviceReport.intercooler.isNullOrEmpty()
            val showThirteenthBox = !serviceReport.waterInletTemp.isNullOrEmpty()
            val showFourteenthBox = !serviceReport.waterOutletTemp.isNullOrEmpty()
            val textYOffset = 45




















//            canvas2.drawText(boxTextSecondBox, (xPosPage2 + 20), (topPositionPage2SecondBox + textYPositionOffsetPage2SecondBox), boxtext)
//            canvas2.drawText(boxTextNineBox, (xPosPage2 + 530), (topPositionPage2SecondBox + textYPositionOffsetPage2SecondBox), boxtext)
//            canvas2.drawText(boxTextSecondBoxx, (xPosPage2 + 410), (topPositionPage2SecondBox + textYPositionOffsetPage2SecondBox), boxtextunit
//            )
//            canvas2.drawText(
//                boxTextNineBoxx,
//                (xPosPage2 + 890),
//                (topPositionPage2SecondBox + textYPositionOffsetPage2SecondBox),
//                boxtextunit
//            )




//// Define the third box properties
//            val topPositionPage2ThirdBox = topPositionPage2SecondBox + boxHeightPage2SecondBox
//            val boxHeightPage2ThirdBox = 70
//            val textYPositionOffsetPage2ThirdBox = 45
//
//// Draw the third box
//            canvas2.drawRect(
//                xPosPage2,
//                topPositionPage2ThirdBox,
//                (pageWidth - xPosPage2),
//                (topPositionPage2ThirdBox + boxHeightPage2ThirdBox),
//                paintBox3
//            )
//
//// Text for the third box
//
//
//            canvas2.drawText(
//                boxTextThirdBox,
//                (xPosPage2 + 20),
//                (topPositionPage2ThirdBox + textYPositionOffsetPage2ThirdBox),
//                boxtext
//            )
//
//            canvas2.drawText(
//                boxTextUPBox,
//                (xPosPage2 + 530),
//                (topPositionPage2ThirdBox + textYPositionOffsetPage2ThirdBox),
//                boxtext
//            )
//
//
//            canvas2.drawText(
//                boxTextThirdBoxx,
//                (xPosPage2 + 410),
//                (topPositionPage2ThirdBox + textYPositionOffsetPage2ThirdBox),
//                boxtextunit
//            )
//
//            canvas2.drawText(
//                boxTextTBoxx,
//                (xPosPage2 + 890),
//                (topPositionPage2ThirdBox + textYPositionOffsetPage2ThirdBox),
//                boxtextunit
//            )
//
//
//// Update yPosPage2 for the next content after the third box
////            yPosPage2 += boxHeightPage2ThirdBox
//
//// Define the fourth box properties
//            val topPositionPage2FourthBox = topPositionPage2ThirdBox + boxHeightPage2ThirdBox
//            val boxHeightPage2FourthBox = 70
//            val textYPositionOffsetPage2FourthBox = 45
//            val paintBox4FourthBox = Paint().apply { color = getColor(R.color.bgtext) }  // Change background color as needed
//
//// Draw the fourth box
//            canvas2.drawRect(
//                xPosPage2,
//                topPositionPage2FourthBox,
//                (pageWidth - xPosPage2),
//                (topPositionPage2FourthBox + boxHeightPage2FourthBox),
//                paintBox2
//            )
//
//// Text for the fourth box
//
//
//
//
//
//            canvas2.drawText(
//                boxTextFourthBox,
//                (xPosPage2 + 20),
//                (topPositionPage2FourthBox + textYPositionOffsetPage2FourthBox),
//                boxtext
//            )
//            canvas2.drawText(
//                boxTextOThBox,
//                (xPosPage2 + 530),
//                (topPositionPage2FourthBox + textYPositionOffsetPage2FourthBox),
//                boxtext
//            )
//
//
//
//            canvas2.drawText(
//                boxText4Boxx,
//                (xPosPage2 + 410),
//                (topPositionPage2FourthBox + textYPositionOffsetPage2FourthBox),
//                boxtextunit
//            )
//            canvas2.drawText(
//                boxTextOBoxx,
//                (xPosPage2 + 890),
//                (topPositionPage2FourthBox + textYPositionOffsetPage2FourthBox),
//                boxtextunit
//            )
//
//
//            val topPositionPage2FifthBox = topPositionPage2FourthBox + boxHeightPage2FourthBox
//            val boxHeightPage2FifthBox = 70
//            val textYPositionOffsetPage2FifthBox = 45
//
//// Draw the fifth box
//            canvas2.drawRect(
//                xPosPage2,
//                topPositionPage2FifthBox,
//                (pageWidth - xPosPage2),
//                (topPositionPage2FifthBox + boxHeightPage2FifthBox),
//                paintBox3
//            )
//
//// Text for the fifth box
//
//
//
//            canvas2.drawText(
//                boxTextFifthBox,
//                (xPosPage2 + 20),
//                (topPositionPage2FifthBox + textYPositionOffsetPage2FifthBox),
//                boxtext
//            )
//
//            canvas2.drawText(
//                boxTextOTEBox,
//                (xPosPage2 + 530),
//                (topPositionPage2FifthBox + textYPositionOffsetPage2FifthBox),
//                boxtext
//            )
//
//            canvas2.drawText(
//                boxText5Boxx,
//                (xPosPage2 + 410),
//                (topPositionPage2FifthBox + textYPositionOffsetPage2FifthBox),
//                boxtextunit
//            )
//
//            canvas2.drawText(
//                boxTextasBoxx,
//                (xPosPage2 + 890),
//                (topPositionPage2FifthBox + textYPositionOffsetPage2FifthBox),
//                boxtextunit
//            )
//
//
//// Update yPosPage2 for the next content after the fifth box
////            yPosPage2 += boxHeightPage2FifthBox + 30
//
//// Define the sixth box properties
//            val topPositionPage2SixthBox = topPositionPage2FifthBox + boxHeightPage2FifthBox
//            val boxHeightPage2SixthBox = 70
//            val textYPositionOffsetPage2SixthBox = 45
//            val paintBox6SixthBox = Paint().apply { color = getColor(R.color.bgtext) }  // Change background color as needed
//
//// Draw the sixth box
//            canvas2.drawRect(
//                xPosPage2,
//                topPositionPage2SixthBox,
//                (pageWidth - xPosPage2),
//                (topPositionPage2SixthBox + boxHeightPage2SixthBox),
//                paintBox2
//            )
//
//// Text for the sixth box
//
//
//            canvas2.drawText(
//                boxTextSixthBox,
//                (xPosPage2 + 20),
//                (topPositionPage2SixthBox + textYPositionOffsetPage2SixthBox),
//                boxtext
//            )
//
//            canvas2.drawText(
//                boxTextOTE2Box,
//                (xPosPage2 + 530),
//                (topPositionPage2SixthBox + textYPositionOffsetPage2SixthBox),
//                boxtext
//            )
//
//
//            canvas2.drawText(
//                boxText6Boxx,
//                (xPosPage2 + 410),
//                (topPositionPage2SixthBox + textYPositionOffsetPage2SixthBox),
//                boxtextunit
//            )
//            canvas2.drawText(
//                boxTextOTEBoxx,
//                (xPosPage2 + 890),
//                (topPositionPage2SixthBox + textYPositionOffsetPage2SixthBox),
//                boxtextunit
//            )
//
//
//
//
//
//// Define the seventh box properties
//            val topPositionPage2SeventhBox = topPositionPage2SixthBox + boxHeightPage2SixthBox
//            val boxHeightPage2SeventhBox = 70
//            val textYPositionOffsetPage2SeventhBox = 45
//            val paintBox7SeventhBox = Paint().apply { color = getColor(R.color.boxbg1) }  // Change background color as needed
//
//// Draw the seventh box
//            canvas2.drawRect(
//                xPosPage2,
//                topPositionPage2SeventhBox,
//                (pageWidth - xPosPage2),
//                (topPositionPage2SeventhBox + boxHeightPage2SeventhBox),
//                paintBox3
//            )
//
//// Text for the seventh box
//
//            canvas2.drawText(
//                boxTextSeventhBox,
//                (xPosPage2 + 20),
//                (topPositionPage2SeventhBox + textYPositionOffsetPage2SeventhBox),
//                boxtext
//            )
//            canvas2.drawText(
//                boxTextCWTBox,
//                (xPosPage2 + 530),
//                (topPositionPage2SeventhBox + textYPositionOffsetPage2SeventhBox),
//                boxtext
//            )
//
//            canvas2.drawText(
//                boxText7Boxx,
//                (xPosPage2 + 410),
//                (topPositionPage2SeventhBox + textYPositionOffsetPage2SeventhBox),
//                boxtextunit
//            )
//            canvas2.drawText(
//                boxTextCWTCBoxx,
//                (xPosPage2 + 890),
//                (topPositionPage2SeventhBox + textYPositionOffsetPage2SeventhBox),
//                boxtextunit
//            )
//            val topPositionPage2eIGHTBox = topPositionPage2SeventhBox + boxHeightPage2SeventhBox
//            val boxHeightPage2EightBox = 70
//            val textYPositionOffsetPage2EightBox = 45
//
//            canvas2.drawRect(
//                xPosPage2,
//                topPositionPage2eIGHTBox,
//                (pageWidth - xPosPage2),
//                (topPositionPage2eIGHTBox + boxHeightPage2EightBox),
//                paintBox2
//            )
//
//            canvas2.drawText(
//                boxTextEighthBox,
//                (xPosPage2 + 20),
//                (topPositionPage2eIGHTBox + textYPositionOffsetPage2EightBox),
//                boxtext
//            )
//
//            canvas2.drawText(
//                boxText8Boxx,
//                (xPosPage2 + 410),
//                (topPositionPage2eIGHTBox + textYPositionOffsetPage2EightBox),
//                boxtextunit
//            )
            // Calculate the positions for the vertical line
            val verticalLineX = xPosPage2 + (pageWidth - xPosPage2) / 2
            val verticalLineStartY = topPositionPage2+70  // Top of the second box
            val verticalLineEndY = topPositionPage2+40 + boxHeightPage2 + 30 + 70 * 6  // Bottom of the seventh box (adjust based on your box heights)

// Define paint for the vertical line
            val verticalLinePaint = Paint().apply {
                color = getColor(R.color.primecolor)  // Replace with your line color
                strokeWidth = 2f  // Adjust line width as needed
            }

// Draw the vertical line
            canvas2.drawLine(
                verticalLineX,
                verticalLineStartY.toFloat(),
                verticalLineX,
                verticalLineEndY.toFloat(),
                verticalLinePaint
            )

//            AKKI
//            ================================================================================================




//            yPosPage2 += topPositionPage2eIGHTBox
//            yPosPage2 = topPositionPage2eIGHTBox + boxHeightPage2EightBox + 60

//
            val recommendedTitle = "RECOMMENDATION & TIPS"
            val tipsText = serviceReport.recommend.toString()

// Draw "RECOMMENDATION & TIPS" title
            canvas2.drawText(recommendedTitle, xPosPage2, yPosPage2, text1)
            yPosPage2 += text1.descent() - text1.ascent()

// Define the maximum width for the tips text
            val maxWidthb = pageWidth - 2 * xPosPage2

// Create StaticLayout for the entire tips text
            val staticLayoutb = StaticLayout.Builder.obtain(tipsText, 0, tipsText.length, observationPaint, maxWidthb.toInt())
                .setAlignment(Layout.Alignment.ALIGN_NORMAL)
                .setLineSpacing(0f, 1.2f)
                .setIncludePad(true)
                .build()

// Draw the tips text
            canvas2.save()
            canvas2.translate(xPosPage2, yPosPage2 - 30)
            staticLayoutb.draw(canvas2)
            canvas2.restore()

// Calculate the y-position after the "RECOMMENDATION & TIPS" text
            yPosPage2 += staticLayoutb.height + 40 // Add spacing after the text

// Draw a line after the text
            val lineStartXabc = xPosPage2
            val lineEndXabc = pageWidth - xPosPage2
            val lineYabc = yPosPage2 -30// Position the line at the updated yPosPage2

            canvas2.drawLine(lineStartXabc, lineYabc, lineEndXabc, lineYabc, linePaint)

// Update yPosPage2 for any further drawing
            yPosPage2 += 10 // Add a small margin after the line if needed
            val signatureFieldWidth = (pageWidth - 2 * xPosPage2) / 2
            val signatureFieldHeight = 80 // Set desired height for signature fields

            val signatureBoxWidth = 450
            val signatureBoxHeight = 150

// Paint for the grey background
            val backgroundPaintttt = Paint().apply {
                color = getColor(R.color.bgtext)

            }

// Paint for the dotted border
            val dottedBorderPaint = Paint().apply {
                color = Color.BLACK
                style = Paint.Style.STROKE
                pathEffect = DashPathEffect(floatArrayOf(10f, 10f), 0f)
                strokeWidth = 3f
            }

// Paint for the text
            val textPaint = Paint().apply {
                color = Color.BLACK
                textSize = 30f
                typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
            }

// Coordinates for the QAS Engineer Signature box
            val signatureBoxLeft = xPosPage2
            val signatureBoxTop = yPosPage2 + 50
            val signatureBoxRight = signatureBoxLeft + signatureBoxWidth
            val signatureBoxBottom = signatureBoxTop + signatureBoxHeight

// Draw the grey background
            canvas2.drawRect(signatureBoxLeft.toFloat(), signatureBoxTop.toFloat(), signatureBoxRight.toFloat(), signatureBoxBottom.toFloat(), backgroundPaintttt)

// Draw the dotted border
            canvas2.drawRect(signatureBoxLeft.toFloat(), signatureBoxTop.toFloat(), signatureBoxRight.toFloat(), signatureBoxBottom.toFloat(), dottedBorderPaint)

// Draw the text for QAS Engineer Signature
            val text34 = "QAS ENGINEER SIGNATURE:"
            canvas2.drawText(text34, signatureBoxLeft.toFloat(), signatureBoxTop.toFloat() - 30, textPaint)

// Coordinates for the Customer Signature box
            val customerSignatureBoxLeft = xPosPage2 +35+ signatureFieldWidth
            val customerSignatureBoxTop = yPosPage2+50
            val customerSignatureBoxRight = customerSignatureBoxLeft + signatureBoxWidth
            val customerSignatureBoxBottom = customerSignatureBoxTop + signatureBoxHeight

// Draw the grey background
            canvas2.drawRect(customerSignatureBoxLeft.toFloat(), customerSignatureBoxTop.toFloat(), customerSignatureBoxRight.toFloat(), customerSignatureBoxBottom.toFloat(), backgroundPaintttt)

// Draw the dotted border
            canvas2.drawRect(customerSignatureBoxLeft.toFloat(), customerSignatureBoxTop.toFloat(), customerSignatureBoxRight.toFloat(), customerSignatureBoxBottom.toFloat(), dottedBorderPaint)

// Draw the text for Customer Signature
            val text3 = "CUSTOMER SIGNATURE"
            canvas2.drawText(text3, customerSignatureBoxLeft.toFloat(), customerSignatureBoxTop.toFloat() - 30, textPaint)

// Load and draw the image in the QAS Engineer Signature box
            val imagePath = file
            val bitmap = BitmapFactory.decodeFile(imagePath.toString())
            bitmap?.let {
                val resizedBitmap = Bitmap.createScaledBitmap(it, signatureBoxWidth, signatureBoxHeight, true)
                canvas2.drawBitmap(resizedBitmap, signatureBoxLeft.toFloat(), signatureBoxTop.toFloat(), null)
            }

// Load and draw the image in the Customer Signature box
            val customerImagePath = custfile
            val customerBitmap = BitmapFactory.decodeFile(customerImagePath.toString())
            customerBitmap?.let {
                val resizedCustomerBitmap = Bitmap.createScaledBitmap(it, signatureBoxWidth, signatureBoxHeight, true)
                canvas2.drawBitmap(resizedCustomerBitmap, customerSignatureBoxLeft.toFloat(), customerSignatureBoxTop.toFloat(), null)
            }
            val nameYPos = signatureBoxBottom + 20



            val maxWidthtext = 450f

// Define the texts

            val qasEngineerName = "Engineer Name : ${serviceReport.engineerName.toString()}"
            val customerName ="Customer Name : ${binding.Customername.text.toString()}"

// Draw the texts with max width
            drawTextWithMaxWidth(canvas2, qasEngineerName, maxWidthtext, signatureBoxLeft.toFloat(), nameYPos + 30.toFloat(), text13)
            drawTextWithMaxWidth(canvas2, customerName, maxWidthtext, customerSignatureBoxLeft.toFloat(), nameYPos + 30.toFloat(), text13)


            yPosPage2 = (nameYPos.toInt() + text1.textSize.toInt() + 20).toFloat()


            receipt.finishPage(page2)

// Create the third page
            val receiptPage3 = PageInfo.Builder(pageWidth, pageHeight, 3).create()
            val page3 = receipt.startPage(receiptPage3)
            val canvas3 = page3.canvas



// Draw title on the third page
            val page3title = "Compressor Condition Before Services"
            val topMarginthird = convertSdpToPixels(10)
            val xPosPage3 = 50f
            var yPosPage3 = 50f + topMarginthird



// Draw title
            canvas3.drawText(page3title, xPosPage3, yPosPage3, text1)
            yPosPage3 += 30
            val startX = 50f
            val startY = 100f
            val padding = 20f // Padding between grid items
            val gridSize = 2 // Number of items per row or column in the grid
            val gridItemWidth = (pageWidth - startX * 2 - padding * (gridSize - 1)) / gridSize // Adjusted width of each grid item
            val gridItemHeight = 500f // Desired height for each grid item
            val backgroundPaint = Paint().apply {
                color = getColor(R.color.boxbg3)
                style = Paint.Style.FILL
            }
//            canvas3.drawRect(startX, startY, pageWidth - startX, pageHeight - startY, backgroundPaint)

// Example positioning variables



// Draw images from imageUriList in a 2-row grid with adjusted dimensions
            for ((index, bitmap) in imageUriList.withIndex()) {
                val column = index % gridSize
                val row = index / gridSize
                val xPos = startX + column * (gridItemWidth + padding)
                val yPos = startY + row * (gridItemHeight + padding)

                val scaledBitmap = Bitmap.createScaledBitmap(bitmap, gridItemWidth.toInt(), gridItemHeight.toInt(), true)
                canvas3.drawBitmap(scaledBitmap, xPos, yPos, backgroundPaint)
            }





            receipt.finishPage(page3)

                try {
                    val randomNumber = Random.nextInt(1000)
                    val fileName = "QAS$randomNumber.pdf"
                    val folderName = "zz"

                    val downloadFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    val folder = File(downloadFolder, folderName)
                    if (!folder.exists()) {
                        folder.mkdirs()  // creates parent directories if not exists
                    }

                    filepdf =  File(folder, fileName)
                    receipt.writeTo(FileOutputStream(filepdf))


                    ApiCall()



//                    try {
////                        receipt.writeTo(FileOutputStream(filepdf))
//                        Log.d("TAG", "Akki123: "+filepdf)
//                        ApiCall()
//
//                    } catch (e: FileNotFoundException) {
//                        Log.e("#Exception=====>>>123", e.message!!)
//
//                        Log.d("TAG", "Akki123: "+filepdf)
//
//                        Toast.makeText(
//                            this,
//                            "PDF file Not generate.",
//                            Toast.LENGTH_SHORT
//                        ).show()
//                        e.printStackTrace()
//                    }
                    receipt.close()

                } catch (e: java.lang.Exception) {
                    Toast.makeText(this, "Error==" + e.message, Toast.LENGTH_SHORT).show()
                    Log.e("#ExceptionError===>>>", e.message!!)
                    e.printStackTrace()
                }

        } catch (e: java.lang.Exception) {
            Toast.makeText(this, "E==" + e.message, Toast.LENGTH_SHORT).show()
            Log.e("#Exception", e.message!!)
            e.printStackTrace()
        }

    }

    private fun ApiCall() {
        binding.progressBar.visibility = View.VISIBLE




        val qasEngineerSignaturePath = file
        val customerSignaturePath = custfile
        val uploadpdf = filepdf


        val qasEngineerSignature = prepareFilePart("qasengineersignature", qasEngineerSignaturePath.toString())
        val customerSignature = prepareFilePart("customersignature", customerSignaturePath.toString())

        val imagelist = prepareImageParts("image[]", imagePaths)
        val requestFile = uploadpdf!!.asRequestBody("uploadpdf".toMediaTypeOrNull())
        pdfBody = MultipartBody.Part.createFormData("uploadpdf", uploadpdf!!.name, requestFile)
        Log.d("TAG", "ApiCall: "+pdfBody)







        val custidPart = createPartFromString(custid)
        val personNamePart = createPartFromString(serviceReport.personName)
        val startDatePart = createPartFromString(serviceReport.startDate)
        val endDatePart = createPartFromString(serviceReport.endDate)
        val engineerNamePart = createPartFromString(serviceReport.engineerName)
        val compressorModelPart = createPartFromString(serviceReport.compressorModel)
        val serialNoPart = createPartFromString(serviceReport.serialNo)
        val runningHourPart = createPartFromString(serviceReport.runningHour)
        val loadingHourPart = createPartFromString(serviceReport.loadingHour)
        val complaintPart = createPartFromString(serviceReport.complaint)
        val observationsPart = createPartFromString(serviceReport.observations)
        val actionPart = createPartFromString(serviceReport.action)
        val recommendPart = createPartFromString(serviceReport.recommend)
        val CompressorOutletTemprature = createPartFromString(serviceReport.CompressorOutletTemprature)
        val WorkingPressure = createPartFromString(serviceReport.WorkingPressure)
        val LoadingPressure = createPartFromString(serviceReport.LoadingPressure)
        val UnloadingPressure = createPartFromString(serviceReport.UnloadingPressure)
        val OilPressure = createPartFromString(serviceReport.OilPressure)
        val Temprature = createPartFromString(serviceReport.Temprature)
        val DpAirFilter = createPartFromString(serviceReport.DpAirFilter)
        val firstststageoutlettemprature = createPartFromString(serviceReport.firstststageoutlettemprature)
        val secndstageinlettemprature = createPartFromString(serviceReport.secndstageinlettemprature)
        val secondOutletTemp = createPartFromString(serviceReport.secondOutletTemp)
        val intercooler = createPartFromString(serviceReport.intercooler)
        val waterInletTemp = createPartFromString(serviceReport.waterInletTemp)
        val waterOutletTemp = createPartFromString(serviceReport.waterOutletTemp)
        val customername = createPartFromString(binding.Customername.text.toString())
        val reportsendmailstatus = createPartFromString(reportstatus)


        handler.post {
            val call = RetrofitClient.instance!!.api.createServiceReport(
                custidPart,
                custidPart,
                personNamePart,
                startDatePart,
                endDatePart,
                engineerNamePart,
                compressorModelPart,
                serialNoPart,
                runningHourPart,
                loadingHourPart,
                complaintPart,
                observationsPart,
                actionPart,
                recommendPart,
                CompressorOutletTemprature,
                WorkingPressure,
                LoadingPressure,
                UnloadingPressure,
                OilPressure,
                Temprature,
                DpAirFilter,
                firstststageoutlettemprature,
                secndstageinlettemprature,
                secondOutletTemp,
                intercooler,
                waterInletTemp,
                waterOutletTemp,
                customername,
                reportsendmailstatus,
                qasEngineerSignature,
                customerSignature,
                pdfBody,
                imagelist
            )

            call.enqueue(object : Callback<CreateServiceReportModel> {
                override fun onResponse(
                    call: Call<CreateServiceReportModel>,
                    response: Response<CreateServiceReportModel>
                ) {
                    val createServiceReportModel: CreateServiceReportModel? = response.body()
                    if (response.isSuccessful) {



                        val intent = Intent(this@AttachSingatureScreenActivity, PDFPreviewActivity::class.java)
                        if (filepdf != null) {
                            intent.putExtra("file", filepdf!!.absolutePath)
                            intent.putExtra("reportstatus",reportstatus)
                            intent.putExtra("id",custid)
                            intent.putExtra("companyname",companyname1)
                            Log.d("TAG", "apicall success: ${filepdf!!.absolutePath}")
                            startActivity(intent)
                        } else {
                            Log.e("TAG", "filepdf is null")
                            // Handle the case where filepdf is null, e.g., show an error message or take appropriate action
                        }
                        binding.progressBar.visibility = View.GONE
                        binding.text.visibility = View.VISIBLE

//                            generatePDF()
//                            GetReportList()




                    }
                }

                override fun onFailure(call: Call<CreateServiceReportModel>, t: Throwable) {
                    Log.d("TAG", "failure: " + t.message.toString())
                }
            })

        }
    }

    fun drawTextWithMaxWidth(canvas: Canvas, text: String, maxWidth: Float, x: Float, y: Float, paint: TextPaint) {
        val textWidth = paint.measureText(text)

        val ellipsizedText = if (textWidth > maxWidth) {
            TextUtils.ellipsize(text, paint, maxWidth, TextUtils.TruncateAt.END).toString()
        } else {
            text
        }

        canvas.drawText(ellipsizedText, x, y, paint)
    }
//    fun showPdfPreview(pdfFile: File) {
////        val imageView = findViewById<ImageView>(R.id.pdfPreviewImageView)
//
//        try {
//            val fileDescriptor =
//                ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY)
//            val pdfRenderer = PdfRenderer(fileDescriptor)
//
//            if (pdfRenderer.pageCount > 0) {
//                val page = pdfRenderer.openPage(0)
//                val bitmap = Bitmap.createBitmap(page.width, page.height, Bitmap.Config.ARGB_8888)
//                page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
//                imageView.setImageBitmap(bitmap)
//                page.close()
//            }
//
//            pdfRenderer.close()
//            fileDescriptor.close()
//        } catch (e: IOException) {
//            e.printStackTrace()
//        }
//    }



    fun convertSdpToPixels(sdpValue: Int): Float {
        val scale = resources.displayMetrics.density
        return (sdpValue * scale + 0.5f)
    }



    private fun printPdf(filename: String) {
        val file = File(filename)
        val uri = FileProvider.getUriForFile(
            this,
            "com.app.qualityairsolution",
            file
        )
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setDataAndType(uri, "application/pdf")
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        val choose = Intent.createChooser(intent, "Open With")
        try {
            startActivity(choose)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }


     fun prepareFilePart(partName: String, filePath: String?): MultipartBody.Part? {
        filePath?.let {
            val file = File(it)
            if (file.exists()) {
                val requestFile = RequestBody.create("image/*".toMediaTypeOrNull(), file)
                return MultipartBody.Part.createFormData(partName, file.name, requestFile)
            } else {
                Log.e("TAG", "File not found at path: $filePath")
                return null
            }
        }
        Log.e("TAG", "File path is null or empty")
        return null
    }
    private fun prepareFilePart2(partName: String, filePath: String?): MultipartBody.Part? {
        filePath?.let {
            val file = File(it)
            if (file.exists()) {
                val requestFile = RequestBody.create("image/*".toMediaTypeOrNull(), file)
                return MultipartBody.Part.createFormData(partName, file.name, requestFile)
            } else {
                Log.e("TAG", "File not found at path: $filePath")
                return null
            }
        }
        Log.e("TAG", "File path is null or empty")
        return null
    }

    //for list of image
    private fun prepareImageParts(
        partName: String,
        filePaths: List<String>
    ): List<MultipartBody.Part> {
        filePaths.forEach { filePath ->
            val file = File(filePath)
            if (file.exists()) {
                // Create request body from file
                val requestFile = RequestBody.create("image/*".toMediaTypeOrNull(), file)
                // Create multipart part
                val part = MultipartBody.Part.createFormData(partName, file.name, requestFile)
                // Add part to list
                imageParts.add(part)
            } else {
                Log.e("TAG", "File not found at path: $filePath")
            }
        }
        return imageParts
    }


    fun createPartFromString(descriptionString: String): RequestBody {
        return descriptionString.toRequestBody("text/plain".toMediaTypeOrNull())
    }


    override fun onImageRemove(position: Int) {
        binding.attachimage2.visibility = View.GONE
        binding.attachimage.visibility = View.VISIBLE
        imageUriList.removeAt(position)
        imagePaths.removeAt(position)
        adapter.notifyItemRemoved(position)
        adapter.notifyItemRangeChanged(position, imageUriList.size)

        if (imageUriList.isEmpty()) {
            binding.imageBox.visibility = View.GONE
        }
    }

    private fun showSelectImageDialog() {
        lateinit var dialog: Dialog
        dialog = Dialog(this, R.style.RoundedCornersDialog)
        dialog.setTitle("More App")
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setCancelable(true)
        dialog.setContentView(R.layout.layout_select_photo)
        val ivCamera: TextView = dialog.findViewById(R.id.ivCamera)
        val ivGallary: TextView = dialog.findViewById(R.id.ivGallary)

        ivCamera.setOnClickListener {
            openCamera()

            dialog.dismiss()
        }
        ivGallary.setOnClickListener {
            openGallery()

            dialog.dismiss()
        }
        dialog.show()

    }

    private fun isStoragePermisssionGranted(): Boolean {
        var granted = false

        granted = if (VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) &&
                (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
            ) {
                true
            } else {
                false
            }
        } else {
            true
        }
        return granted
    }

    private fun requestStoragePermission() {
        val permissions = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
        )
        ActivityCompat.requestPermissions(
            this,
            permissions,
            MY_PERMISSIONS_REQUEST_STORAGE_PERMISSIONS
        )
    }

    private fun takeScreenshot() {

            val bitmap = Bitmap.createBitmap(
                binding.signatureView.width,
                binding.signatureView.height,
                Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(bitmap)
            binding.signatureView.draw(canvas)
            saveBitmap(bitmap)



    }
    private fun custtakeScreenshot() {
            val bitmap2 = Bitmap.createBitmap(
                binding.custsignatureView.width,
                binding.custsignatureView.height,
                Bitmap.Config.ARGB_8888
            )
            val canvas2 = Canvas(bitmap2)




            binding.custsignatureView.draw(canvas2)

            // Save bitmap to storage
            saveBitmap2(bitmap2)



    }

    private fun saveBitmap(bitmap: Bitmap) {
        ersignsaved = true
        val directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES)

        // Create directory if it doesn't exist
        if (!directory!!.exists()) {
            directory.mkdirs()
        }

        // Create a file to save the screenshot
        file = File(directory, "er_draw_view_screenshot_${System.currentTimeMillis()}.png")
        Log.d("TAG", "saveBitmap====>>>>: " + file)
        try {
            // Convert bitmap to byte array
            val outputStream: OutputStream = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, outputStream)
            outputStream.flush()
            outputStream.close()
//            jpgFile = convertPngToJpg(file!!)


        } catch (e: Exception) {
            e.printStackTrace()
        }
    }



    private fun saveBitmap2(bitmap2: Bitmap) {
        custsignsaved = true
        val directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES)

        if (!directory!!.exists()) {
            directory.mkdirs()
        }

        // Create a file to save the screenshot
        custfile = File(directory, "cust_draw_view_screenshot_${System.currentTimeMillis()}.png")

        Log.d("TAG", "saveBitmap2======>>>>>: "+custfile)
        try {
            val outputStream: OutputStream = FileOutputStream(custfile)
            bitmap2.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
            outputStream.flush()
            outputStream.close()
//            custjpgFile = convertPngToJpg2(custfile!!)
            Log.d("TAG", "saveBitmap2: "+custjpgFile!!.path)


        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private fun checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
                checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED
            ) {

                requestPermissions(
                    arrayOf(
                        Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_MEDIA_IMAGES
                    ), PERMISSION_REQUEST_CODE
                )
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_IMAGE_CAPTURE -> {
                    val imageBitmap = BitmapFactory.decodeFile(currentPhotoPath)
                    val compressedBitmap = compressBitmap(imageBitmap, 40) // Adjust the quality as needed (0-100)



                    // Add the captured image to your list and paths
                    addImageToList(compressedBitmap)
                    imagePaths.add(currentPhotoPath!!)
//                    // If capturing an image from camera
//                    val imageBitmap = data?.extras?.get("data") as Bitmap
//                    val tempFile = createTempFile("camera_image", ".jpg", externalCacheDir).apply {
//                        outputStream().use {
//                            imageBitmap.compress(
//                                Bitmap.CompressFormat.JPEG,
//                                100,
//                                it
//                            )
//                        }
//                    }
//                    val filePath = tempFile.absolutePath
//                    addImageToList(imageBitmap)
//                    imagePaths.add(filePath)

                }

                REQUEST_IMAGE_PICK -> {
                    val imageBitmaps = mutableListOf<Bitmap>()
                    val filePaths = mutableListOf<String>()

                    // Handle multiple selected images
                    if (data?.clipData != null) {
                        val clipData = data.clipData
                        val itemCount = clipData!!.itemCount.coerceAtMost(MAX_IMAGES)
                        for (i in 0 until itemCount) {
                            val uri = clipData.getItemAt(i).uri
                            val filePath = getRealPathFromURI(uri)
                            val imageBitmap =
                                MediaStore.Images.Media.getBitmap(this.contentResolver, uri)
                            imageBitmaps.add(imageBitmap)
                            filePaths.add(filePath!!)
                        }
                    } else if (data?.data != null) {
                        // Handle single selected image (fallback)
                        val uri = data.data
                        val filePath = getRealPathFromURI(uri!!)
                        val imageBitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, uri)
                        val compressedBitmap = compressBitmap(imageBitmap, 40) // Adjust the quality as needed (0-100)

                        imageBitmaps.add(compressedBitmap)
                        filePaths.add(filePath!!)
                    }

                    // Add images to list and display (limit to MAX_IMAGES)
                    for (bitmap in imageBitmaps) {
                        if (imagePaths.size < MAX_IMAGES) {
                            addImageToList(bitmap)
                        }
                    }
                    // Add file paths to list (limit to MAX_IMAGES)
                    for (filePath in filePaths) {
                        if (imagePaths.size < MAX_IMAGES) {
                            imagePaths.add(filePath)
                        }
                    }

                    // Notify user if attempted to select more than MAX_IMAGES
                    if (imageBitmaps.size > MAX_IMAGES || filePaths.size > MAX_IMAGES) {
                        Toast.makeText(
                            this,
                            "You can select up to $MAX_IMAGES images.",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
        }
    }
    private fun compressBitmap(bitmap: Bitmap, quality: Int): Bitmap {
        val stream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream)
        val byteArray = stream.toByteArray()
        return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
    }


    // Function to get real path from URI
    private fun getRealPathFromURI(uri: Uri?): String? {
        var filePath: String? = null
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = uri?.let { contentResolver.query(it, projection, null, null, null) }
        cursor?.let {
            if (it.moveToFirst()) {
                val columnIndex = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                filePath = it.getString(columnIndex)
            }
            it.close()
        }
        return filePath
    }


    private fun addImageToList(bitmap: Bitmap) {
        binding.imageBox.visibility = View.VISIBLE
        imageUriList.add(bitmap)
        adapter.notifyDataSetChanged()
    }


    //    private fun openGallery() {
//        Intent(
//            Intent.ACTION_PICK,
//            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
//        ).also { pickPictureIntent ->
//            startActivityForResult(pickPictureIntent, REQUEST_IMAGE_PICK)
//        }
//    }
    private fun openGallery() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_IMAGE_PICK)
    }


    private fun openCamera() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // Ensure that there's a camera activity to handle the intent
            takePictureIntent.resolveActivity(packageManager)?.also {
                // Create the File where the photo should go
                val photoFile: File? = try {
                    createImageFile()
                } catch (ex: IOException) {
                    // Error occurred while creating the File
                    ex.printStackTrace()
                    null
                }
                // Continue only if the File was successfully created
                photoFile?.also {
                    val photoURI: Uri = FileProvider.getUriForFile(
                        this,
                        "com.app.qualityairsolution",
                        it
                    )
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
                }
            }
        }
    }

    @Throws(IOException::class)
    private fun createImageFile(): File {
        // Create an image file name
        val timeStamp: String =
            SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "JPEG_${timeStamp}_", /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
        ).apply {
            // Save a file: path for use with ACTION_VIEW intents
            currentPhotoPath = absolutePath
        }
    }


}
Editor is loading...
Leave a Comment