package com.example.bdkipoc.transaction;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.bdkipoc.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * ResultTransactionActivity - Enhanced Receipt-style Display using activity_receipt.xml
 * Shows EMV/Card transaction results using the same layout as QRIS receipts
 */
public class ResultTransactionActivity extends AppCompatActivity {
    private static final String TAG = "ResultTransaction";
    
    // ✅ UI Components using activity_receipt.xml IDs
    private LinearLayout backNavigation;
    private ImageView backArrow;
    private TextView toolbarTitle;
    
    // Receipt details
    private TextView merchantName;
    private TextView merchantLocation;
    private TextView midText;
    private TextView tidText;
    private TextView transactionNumber;
    private TextView transactionDate;
    private TextView paymentMethod;
    private TextView cardType;
    private TextView transactionTotal;
    private TextView taxPercentage;
    private TextView serviceFee;
    private TextView finalTotal;
    
    // Action buttons
    private LinearLayout printButton;
    private LinearLayout emailButton;
    private Button finishButton;
    
    // Data from intent
    private String transactionAmount;
    private String cardTypeFromIntent;
    private boolean emvMode;
    private String referenceId;
    private String cardNo;
    private String midtransResponse;
    private boolean paymentSuccess;
    private String emvCardholderName;
    private String emvAid;
    private String emvExpiry;
    
    // Internal data
    private JSONObject responseJsonData;
    private boolean isNavigating = false;
    
    // Receipt calculation data
    private long subtotalAmount = 0;
    private long taxAmount = 0;
    private long serviceFeeAmount = 500; // Default service fee
    private double taxPercentageValue = 0.11; // 11% tax
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // ✅ CRITICAL: Use the same layout as ReceiptActivity
        setContentView(R.layout.activity_receipt);
        
        Log.d(TAG, "=== RESULT TRANSACTION ACTIVITY STARTED ===");
        Log.d(TAG, "✅ Using activity_receipt.xml layout");
        
        initViews();
        extractIntentData();
        debugAllDataSources();
        setupListeners();
        calculateAmounts();
        displayReceiptData();
        
        logTransactionDetails();
    }
    
    private void initViews() {
        // ✅ Initialize views using activity_receipt.xml IDs
        
        // Navigation
        backNavigation = findViewById(R.id.back_navigation);
        backArrow = findViewById(R.id.backArrow);
        toolbarTitle = findViewById(R.id.toolbarTitle);
        
        // Receipt details
        merchantName = findViewById(R.id.merchant_name);
        merchantLocation = findViewById(R.id.merchant_location);
        midText = findViewById(R.id.mid_text);
        tidText = findViewById(R.id.tid_text);
        transactionNumber = findViewById(R.id.transaction_number);
        transactionDate = findViewById(R.id.transaction_date);
        paymentMethod = findViewById(R.id.payment_method);
        cardType = findViewById(R.id.card_type);
        transactionTotal = findViewById(R.id.transaction_total);
        taxPercentage = findViewById(R.id.tax_percentage);
        serviceFee = findViewById(R.id.service_fee);
        finalTotal = findViewById(R.id.final_total);
        
        // Action buttons
        printButton = findViewById(R.id.print_button);
        emailButton = findViewById(R.id.email_button);
        finishButton = findViewById(R.id.finish_button);
        
        Log.d(TAG, "✅ All views initialized using activity_receipt.xml");
    }
    
    private void extractIntentData() {
        Intent intent = getIntent();
        
        transactionAmount = intent.getStringExtra("TRANSACTION_AMOUNT");
        cardTypeFromIntent = intent.getStringExtra("CARD_TYPE");
        emvMode = intent.getBooleanExtra("EMV_MODE", false);
        referenceId = intent.getStringExtra("REFERENCE_ID");
        cardNo = intent.getStringExtra("CARD_NO");
        midtransResponse = intent.getStringExtra("MIDTRANS_RESPONSE");
        paymentSuccess = intent.getBooleanExtra("PAYMENT_SUCCESS", true);
        emvCardholderName = intent.getStringExtra("EMV_CARDHOLDER_NAME");
        emvAid = intent.getStringExtra("EMV_AID");
        emvExpiry = intent.getStringExtra("EMV_EXPIRY");
        
        Log.d(TAG, "=== EXTRACTING INTENT DATA ===");
        Log.d(TAG, "Card Type: " + cardTypeFromIntent);
        Log.d(TAG, "EMV Mode: " + emvMode);
        Log.d(TAG, "Transaction Amount: " + transactionAmount);
        Log.d(TAG, "Reference ID: " + referenceId);
        Log.d(TAG, "Midtrans Response Length: " + (midtransResponse != null ? midtransResponse.length() : 0));
        
        // Parse Midtrans response if available
        if (midtransResponse != null && !midtransResponse.isEmpty()) {
            try {
                responseJsonData = new JSONObject(midtransResponse);
                Log.d(TAG, "✅ Midtrans Response parsed successfully!");
                
                // Check for bank field specifically
                if (responseJsonData.has("bank")) {
                    String bankValue = responseJsonData.getString("bank");
                    Log.d(TAG, "✅ Bank field found: '" + bankValue + "'");
                } else {
                    Log.w(TAG, "⚠️ No 'bank' field in Midtrans response");
                }
                
            } catch (JSONException e) {
                Log.e(TAG, "❌ Error parsing Midtrans response: " + e.getMessage());
                responseJsonData = null;
            }
        } else {
            Log.w(TAG, "⚠️ No Midtrans response data available");
            responseJsonData = null;
        }
        
        Log.d(TAG, "===============================");
    }
    
    private void setupListeners() {
        // Back navigation
        backNavigation.setOnClickListener(v -> {
            if (isNavigating) return;
            navigateBack();
        });
        
        backArrow.setOnClickListener(v -> {
            if (isNavigating) return;
            navigateBack();
        });
        
        toolbarTitle.setOnClickListener(v -> {
            if (isNavigating) return;
            navigateBack();
        });
        
        // Print button
        printButton.setOnClickListener(v -> {
            showToast("Mencetak struk...");
            printReceipt();
        });
        
        // Email button
        emailButton.setOnClickListener(v -> {
            showToast("Mengirim email...");
            emailReceipt();
        });
        
        // ✅ Finish button - Navigate to new transaction
        finishButton.setOnClickListener(v -> {
            if (isNavigating) return;
            navigateToNewTransaction();
        });
        
        Log.d(TAG, "✅ All click listeners setup");
    }
    
    private void calculateAmounts() {
        try {
            if (transactionAmount != null && !transactionAmount.isEmpty()) {
                subtotalAmount = Long.parseLong(transactionAmount);
            } else {
                subtotalAmount = 3500000; // Default amount for demo
            }
            
            // Calculate tax (11%)
            taxAmount = Math.round(subtotalAmount * taxPercentageValue);
            
            // Service fee is fixed
            serviceFeeAmount = 500;
            
            Log.d(TAG, "Amounts calculated - Subtotal: " + subtotalAmount + 
                      ", Tax: " + taxAmount + ", Service: " + serviceFeeAmount);
            
        } catch (NumberFormatException e) {
            Log.e(TAG, "Error calculating amounts: " + e.getMessage());
            // Set default values
            subtotalAmount = 3500000;
            taxAmount = 385000;
            serviceFeeAmount = 500;
        }
    }
    
    private void displayReceiptData() {
        Log.d(TAG, "=== DISPLAYING RECEIPT DATA ===");
        debugAllDataSources();
        
        // ✅ 1. Set merchant data
        merchantName.setText("TOKO KLONTONG PAK EKO");
        merchantLocation.setText("Ciputat Baru, Tangsel");
        
        // ✅ 2. Set MID and TID
        String tid = extractTidFromResponse();
        midText.setText("MID: " + tid);
        tidText.setText("TID: " + tid);
        
        // ✅ 3. Set transaction number
        String displayTransactionNumber = extractTransactionNumberFromResponse();
        transactionNumber.setText(displayTransactionNumber);
        
        // ✅ 4. Set transaction date
        String displayDate = formatTransactionDate();
        transactionDate.setText(displayDate);
        
        // ✅ 5. Set payment method
        String displayPaymentMethod = getPaymentMethodDisplay();
        paymentMethod.setText(displayPaymentMethod);
        
        // ✅ 6. ENHANCED: Set card type with comprehensive detection
        String displayCardType = getCardTypeDisplay();
        cardType.setText(displayCardType);
        
        // ✅ 7. Set amount details
        NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("id", "ID"));
        
        transactionTotal.setText(formatter.format(subtotalAmount));
        taxPercentage.setText(Math.round(taxPercentageValue * 100) + "%");
        serviceFee.setText(formatter.format(serviceFeeAmount));
        
        // Final total
        long finalTotalAmount = subtotalAmount + taxAmount + serviceFeeAmount;
        finalTotal.setText(formatter.format(finalTotalAmount));
        
        Log.d(TAG, "✅ Receipt data displayed successfully");
        Log.d(TAG, "   Payment Method: " + displayPaymentMethod);
        Log.d(TAG, "   Card Type: " + displayCardType);
        Log.d(TAG, "   Final Total: " + formatter.format(finalTotalAmount));
        Log.d(TAG, "================================");
    }
    
    private String extractTidFromResponse() {
        if (responseJsonData != null && responseJsonData.has("tid")) {
            try {
                return responseJsonData.getString("tid");
            } catch (JSONException e) {
                Log.e(TAG, "Error extracting TID: " + e.getMessage());
            }
        }
        return "123456789901"; // Default TID
    }
    
    private String extractTransactionNumberFromResponse() {
        if (responseJsonData != null) {
            try {
                if (responseJsonData.has("transaction_id")) {
                    String fullTransactionId = responseJsonData.getString("transaction_id");
                    // Extract last 10 digits for display
                    if (fullTransactionId.length() > 10) {
                        return fullTransactionId.substring(fullTransactionId.length() - 10);
                    }
                    return fullTransactionId;
                }
            } catch (JSONException e) {
                Log.e(TAG, "Error extracting transaction number: " + e.getMessage());
            }
        }
        
        // Generate from reference ID or use default
        if (referenceId != null && referenceId.length() > 10) {
            return referenceId.substring(referenceId.length() - 10);
        }
        
        return String.valueOf(System.currentTimeMillis() % 10000000000L);
    }
    
    private String formatTransactionDate() {
        if (responseJsonData != null) {
            try {
                if (responseJsonData.has("transaction_time")) {
                    String transactionTime = responseJsonData.getString("transaction_time");
                    return formatDateForDisplay(transactionTime);
                }
            } catch (JSONException e) {
                Log.e(TAG, "Error extracting transaction time: " + e.getMessage());
            }
        }
        
        // Use current date and time
        return formatDateForDisplay(new Date());
    }
    
    private String formatDateForDisplay(String dateString) {
        try {
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            SimpleDateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy HH:mm", new Locale("id", "ID"));
            Date date = inputFormat.parse(dateString);
            return outputFormat.format(date);
        } catch (Exception e) {
            Log.e(TAG, "Error formatting date: " + e.getMessage());
            return formatDateForDisplay(new Date());
        }
    }
    
    private String formatDateForDisplay(Date date) {
        SimpleDateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy HH:mm", new Locale("id", "ID"));
        return outputFormat.format(date);
    }
    
    private String getPaymentMethodDisplay() {
        if (cardTypeFromIntent == null) return "Kartu Kredit";
        
        switch (cardTypeFromIntent.toUpperCase()) {
            case "EMV_MIDTRANS":
            case "IC":
            case "NFC":
                return emvMode ? "Kartu Kredit (EMV)" : "Kartu Kredit";
            case "DEBIT":
                return emvMode ? "Kartu Debit (EMV)" : "Kartu Debit";
            case "MAGNETIC":
                return "Kartu Kredit";
            default:
                return "Kartu Kredit";
        }
    }
    
    // ✅ ENHANCED: Comprehensive bank detection for EMV transactions
    private String getCardTypeDisplay() {
        Log.d(TAG, "=== DETERMINING CARD TYPE DISPLAY (EMV) ===");
        
        // Priority 1: Get bank from Midtrans response (most accurate)
        if (responseJsonData != null) {
            Log.d(TAG, "✅ Midtrans response available, checking for bank...");
            
            try {
                String bankFromResponse = null;
                
                if (responseJsonData.has("bank")) {
                    bankFromResponse = responseJsonData.getString("bank");
                    Log.d(TAG, "Found 'bank' field: '" + bankFromResponse + "'");
                } else if (responseJsonData.has("issuer")) {
                    bankFromResponse = responseJsonData.getString("issuer");
                    Log.d(TAG, "Found 'issuer' field: '" + bankFromResponse + "'");
                } else if (responseJsonData.has("acquiring_bank")) {
                    bankFromResponse = responseJsonData.getString("acquiring_bank");
                    Log.d(TAG, "Found 'acquiring_bank' field: '" + bankFromResponse + "'");
                }
                
                if (bankFromResponse != null && !bankFromResponse.trim().isEmpty()) {
                    String formattedBank = formatBankName(bankFromResponse);
                    Log.d(TAG, "✅ Bank from Midtrans response: '" + bankFromResponse + "' -> '" + formattedBank + "'");
                    return formattedBank;
                }
                
            } catch (JSONException e) {
                Log.e(TAG, "❌ Error extracting bank from response: " + e.getMessage());
            }
        }
        
        // Priority 2: EMV AID detection
        Log.d(TAG, "Trying EMV AID detection...");
        if (emvAid != null && !emvAid.trim().isEmpty()) {
            String bankFromAid = getBankFromAid(emvAid);
            if (!bankFromAid.equals("BCA")) { // If not default
                Log.d(TAG, "✅ Bank from EMV AID: " + bankFromAid);
                return bankFromAid;
            }
        }
        
        // Priority 3: Card BIN detection
        Log.d(TAG, "Trying Card BIN detection...");
        if (cardNo != null && cardNo.length() >= 6) {
            String cardBin = cardNo.substring(0, 6);
            String bankFromBin = getBankFromComprehensiveBin(cardBin);
            Log.d(TAG, "✅ Bank from BIN (" + cardBin + "): " + bankFromBin);
            return bankFromBin;
        }
        
        Log.d(TAG, "⚠️ Using default bank: BCA");
        Log.d(TAG, "====================================");
        return "BCA"; // Default fallback
    }
    
    // ✅ ENHANCED: Better bank name formatting
    private String formatBankName(String bankName) {
        if (bankName == null || bankName.trim().isEmpty()) {
            return "BCA"; // Default
        }
        
        String formatted = bankName.trim().toUpperCase();
        
        // Handle common bank name variations
        switch (formatted) {
            case "BCA":
            case "BANK BCA":
            case "BANK CENTRAL ASIA":
                return "BCA";
                
            case "MANDIRI":
            case "BANK MANDIRI":
                return "Mandiri";
                
            case "BNI":
            case "BANK BNI":
            case "BANK NEGARA INDONESIA":
                return "BNI";
                
            case "BRI":
            case "BANK BRI":
            case "BANK RAKYAT INDONESIA":
                return "BRI";
                
            case "CIMB":
            case "CIMB NIAGA":
            case "BANK CIMB NIAGA":
                return "CIMB Niaga";
                
            case "DANAMON":
            case "BANK DANAMON":
                return "Danamon";
                
            case "PERMATA":
            case "BANK PERMATA":
                return "Permata";
                
            default:
                return capitalizeFirstLetter(bankName);
        }
    }
    
    private String getBankFromAid(String aid) {
        // AID to Indonesian bank mapping
        if (aid.contains("A0000000031010")) {
            // VISA - check if we have card number for better detection
            if (cardNo != null && cardNo.length() >= 6) {
                return getBankFromComprehensiveBin(cardNo.substring(0, 6));
            }
            return "BCA"; // Default for VISA
        }
        
        if (aid.contains("A0000000041010")) {
            // MASTERCARD
            if (cardNo != null && cardNo.length() >= 6) {
                return getBankFromComprehensiveBin(cardNo.substring(0, 6));
            }
            return "Mandiri"; // Default for Mastercard
        }
        
        return "BCA"; // Ultimate fallback
    }
    
    // ✅ ENHANCED: Comprehensive Indonesian bank BIN mapping
    private String getBankFromComprehensiveBin(String bin) {
        if (bin == null || bin.length() < 4) {
            return "BCA"; // Default
        }
        
        String bin4 = bin.substring(0, 4);
        String bin6 = bin.length() >= 6 ? bin.substring(0, 6) : bin4;
        
        // BCA patterns
        if (bin4.equals("4621") || bin4.equals("4699") || bin4.equals("5221") || bin4.equals("6277")) {
            return "BCA";
        }
        
        // MANDIRI patterns
        if (bin4.equals("4313") || bin4.equals("5573") || bin4.equals("6011") || bin4.equals("6234")) {
            return "Mandiri";
        }
        
        // BNI patterns  
        if (bin4.equals("4603") || bin4.equals("1946") || bin4.equals("5264")) {
            return "BNI";
        }
        
        // BRI patterns
        if (bin4.equals("4578") || bin4.equals("4479") || bin4.equals("5208")) {
            return "BRI";
        }
        
        // CIMB NIAGA patterns
        if (bin4.equals("4599") || bin4.equals("5249")) {
            return "CIMB Niaga";
        }
        
        // DANAMON patterns
        if (bin4.equals("4055") || bin4.equals("5108")) {
            return "Danamon";
        }
        
        // Default fallback
        Log.d(TAG, "Unknown BIN pattern: " + bin6 + ", using default BCA");
        return "BCA";
    }
    
    private String capitalizeFirstLetter(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
    }
    
    // ✅ Debug methods
    private void debugAllDataSources() {
        Log.d(TAG, "=== DEBUGGING ALL DATA SOURCES ===");
        
        if (responseJsonData != null) {
            Log.d(TAG, "Midtrans Response Available:");
            try {
                java.util.Iterator<String> keys = responseJsonData.keys();
                while (keys.hasNext()) {
                    String key = keys.next();
                    Object value = responseJsonData.get(key);
                    Log.d(TAG, "  " + key + ": " + value);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error iterating response: " + e.getMessage());
            }
        } else {
            Log.d(TAG, "❌ No Midtrans Response Data");
        }
        
        Log.d(TAG, "EMV Data:");
        Log.d(TAG, "  Card Number: " + (cardNo != null ? maskCardNumber(cardNo) : "null"));
        Log.d(TAG, "  EMV AID: " + emvAid);
        Log.d(TAG, "  EMV Cardholder: " + emvCardholderName);
        Log.d(TAG, "  EMV Mode: " + emvMode);
        
        Log.d(TAG, "==================================");
    }
    
    private void logTransactionDetails() {
        Log.d(TAG, "=== RECEIPT DETAILS ===");
        Log.d(TAG, "Reference ID: " + referenceId);
        Log.d(TAG, "Card Number: " + (cardNo != null ? maskCardNumber(cardNo) : "N/A"));
        Log.d(TAG, "Subtotal: " + subtotalAmount);
        Log.d(TAG, "Tax: " + taxAmount);
        Log.d(TAG, "Service Fee: " + serviceFeeAmount);
        Log.d(TAG, "Final Total: " + (subtotalAmount + taxAmount + serviceFeeAmount));
        Log.d(TAG, "======================");
    }
    
    // Action Methods
    private void printReceipt() {
        Log.d(TAG, "Print receipt requested");
        showToast("Fitur cetak akan segera tersedia");
    }
    
    private void emailReceipt() {
        Log.d(TAG, "Email receipt requested");
        
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setType("text/plain");
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Struk Pembayaran - " + extractTransactionNumberFromResponse());
        emailIntent.putExtra(Intent.EXTRA_TEXT, generateEmailContent());
        
        try {
            startActivity(Intent.createChooser(emailIntent, "Kirim Email"));
        } catch (Exception e) {
            Log.e(TAG, "Error sending email: " + e.getMessage());
            showToast("Tidak dapat mengirim email");
        }
    }
    
    private String generateEmailContent() {
        StringBuilder content = new StringBuilder();
        NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("id", "ID"));
        
        content.append("STRUK PEMBAYARAN EMV/CARD\n");
        content.append("==========================\n\n");
        content.append("TOKO KLONTONG PAK EKO\n");
        content.append("Ciputat Baru, Tangsel\n\n");
        content.append("TID: ").append(extractTidFromResponse()).append("\n");
        content.append("Nomor Transaksi: ").append(extractTransactionNumberFromResponse()).append("\n");
        content.append("Tanggal: ").append(formatTransactionDate()).append("\n");
        content.append("Metode: ").append(getPaymentMethodDisplay()).append("\n");
        content.append("Jenis Kartu: ").append(getCardTypeDisplay()).append("\n\n");
        
        if (emvMode && emvCardholderName != null) {
            content.append("DETAIL EMV:\n");
            content.append("Cardholder: ").append(emvCardholderName).append("\n");
            content.append("AID: ").append(emvAid).append("\n\n");
        }
        
        content.append("RINCIAN PEMBAYARAN:\n");
        content.append("Total Transaksi: Rp ").append(formatter.format(subtotalAmount)).append("\n");
        content.append("Pajak (11%): Rp ").append(formatter.format(taxAmount)).append("\n");
        content.append("Biaya Layanan: Rp ").append(formatter.format(serviceFeeAmount)).append("\n");
        content.append("------------------------\n");
        content.append("TOTAL: Rp ").append(formatter.format(subtotalAmount + taxAmount + serviceFeeAmount)).append("\n");
        content.append("\nTerima kasih atas pembayaran Anda!");
        
        return content.toString();
    }
    
    // Navigation Methods
    private void navigateBack() {
        if (isNavigating) return;
        
        Log.d(TAG, "Navigating back");
        isNavigating = true;
        finish();
    }
    
    private void navigateToNewTransaction() {
        if (isNavigating) return;
        
        new AlertDialog.Builder(this)
            .setTitle("Transaksi Baru")
            .setMessage("Apakah Anda ingin melakukan transaksi baru?")
            .setPositiveButton("Ya", (dialog, which) -> {
                performNavigateToNewTransaction();
            })
            .setNegativeButton("Tidak", null)
            .show();
    }
    
    private void performNavigateToNewTransaction() {
        Log.d(TAG, "=== NAVIGATING TO NEW TRANSACTION ===");
        isNavigating = true;
        
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            try {
                Intent intent = new Intent(this, CreateTransactionActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
            } catch (Exception e) {
                Log.e(TAG, "Error navigating to new transaction: " + e.getMessage());
                isNavigating = false;
                showToast("Gagal membuka transaksi baru");
            }
        }, 300);
    }
    
    // Helper Methods
    private String maskCardNumber(String cardNumber) {
        if (cardNumber == null || cardNumber.length() < 8) {
            return cardNumber;
        }
        String first4 = cardNumber.substring(0, 4);
        String last4 = cardNumber.substring(cardNumber.length() - 4);
        return first4 + "****" + last4;
    }
    
    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onBackPressed() {
        if (isNavigating) {
            return;
        }
        navigateBack();
        super.onBackPressed();
    }
    
    @Override
    protected void onDestroy() {
        Log.d(TAG, "ResultTransactionActivity destroyed");
        super.onDestroy();
    }
}