package com.example.temperature;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.app.Activity;

public class MainActivity extends Activity {

    private EditText celsiusInput, fahrenheitInput;
    private boolean isUpdating = false; // Pour éviter les boucles infinies

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        celsiusInput = findViewById(R.id.celsiusInput);
        fahrenheitInput = findViewById(R.id.fahrenheitInput);

        celsiusInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!isUpdating) {
                    isUpdating = true;
                    convertCelsiusToFahrenheit();
                    isUpdating = false;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {}
        });

        fahrenheitInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!isUpdating) {
                    isUpdating = true;
                    convertFahrenheitToCelsius();
                    isUpdating = false;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {}
        });
    }

    private void convertCelsiusToFahrenheit() {
        String celsiusText = celsiusInput.getText().toString();
        if (!celsiusText.isEmpty()) {
            double celsius = Double.parseDouble(celsiusText);
            double fahrenheit = Temperature.celsiusToFahrenheit(celsius);
            fahrenheitInput.setText(String.format("%.2f", fahrenheit));
        } else {
            fahrenheitInput.setText("");
        }
    }

    private void convertFahrenheitToCelsius() {
        String fahrenheitText = fahrenheitInput.getText().toString();
        if (!fahrenheitText.isEmpty()) {
            double fahrenheit = Double.parseDouble(fahrenheitText);
            double celsius = Temperature.fahrenheitToCelsius(fahrenheit);
            celsiusInput.setText(String.format("%.2f", celsius));
        } else {
            celsiusInput.setText("");
        }
    }
}
