package eu.boiert.airtalk;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Intent service;
    private static final String TAG = "MainActivity";

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

        service = new Intent(this, BackgroundService.class);
        startService(service);

        EditText messageBox = findViewById(R.id.message);
        messageBox.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                final String s = (v.getText()).toString();
                Log.d(TAG, s );
                v.setText("");

                //better start sending the message here
                //so ... bind to service, cast IBinder as BackgroundService and call methods.,, then unbind?
                // Right?
                ServiceConnection conn = new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                        Log.d(TAG, "Whee");
                        BackgroundService backgroundService = ((BackgroundService.LocalBinder)service).getService();
                        backgroundService.send(s);
                        unbindService(this);
                    }

                    @Override
                    public void onServiceDisconnected(ComponentName name) {
                        Log.d(TAG, "huh");
                    }
                };
                bindService(service, conn,0);

                return false;
            }
        });
    }

    public void changeState(View button) {
        if (((Switch) button).isChecked()){
            startService(service);
            (findViewById(R.id.message)).setVisibility(View.VISIBLE);
        } else {
            stopService(service);
            (findViewById(R.id.message)).setVisibility(View.INVISIBLE);
        }
    }
}
