package com.zatackcoder.sendingmessagetowhatsapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        final EditText countryCodeET = findViewById(R.id.country_code);
        final EditText mobileET = findViewById(R.id.mobile);
        final EditText messageET = findViewById(R.id.message);

        Button button1 = findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String countryCode = countryCodeET.getText().toString().trim();
                String mobile = mobileET.getText().toString().trim();
                String message = messageET.getText().toString();
                try {
                    Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + countryCode + mobile + "?body=" + message)); // I have appended  message here but it doesn't work use second method to send message as well
                    //sendIntent.putExtra(Intent.EXTRA_TEXT, message);
                    sendIntent.setPackage("com.whatsapp");
                    startActivity(sendIntent);
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "It seems whatsapp not installed on your phone!", Toast.LENGTH_LONG).show();
                }
            }
        });

        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String countryCode = countryCodeET.getText().toString().trim();
                String mobile = mobileET.getText().toString().trim();
                String message = messageET.getText().toString();
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + countryCode + mobile + "&text=" + message));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}