package com.minnecker.futurhouse;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;

import com.tinkerforge.*;

public class Main extends Activity {

    private static String host = "192.168.43.16";
    private static int port = 4223;
    private static BrickStepper doorMotor = new BrickStepper("9p3kGcpYTNb");
    private IPConnection ipcon;
    private static final int doorclosedstep = 14000;
    private static final int dooropendstep = 0;
    private ToggleButton openclose = (ToggleButton) findViewById(R.id.openclosedoor);
    
    
    private void connectToTF(String host, int port) {
        try {
            ipcon = new IPConnection(host, port);
            ipcon.addDevice(doorMotor);
            doorMotor.setMotorCurrent(300);
            doorMotor.setMinimumVoltage(12000);
            doorMotor.enable();
            openclose.setOnClickListener(new OnClickListener() {
    			
    			public void onClick(View v) {
    				if(openclose.isChecked() == true) {
    					//tuer ist offen - schliessen!
    					doorMotor.setSteps(doorclosedstep);
    				}
    				else {
    					//tuer ist geschlossen - oeffnen!
    					doorMotor.setSteps(dooropendstep);
    				}
    			}
    		});
            openclose.setEnabled(true);
        } catch(Exception e) {
            
        }
             
    }
    
    public void endCon(View view) {
    	ipcon.destroy();
    }
	
    public void closedDoor(View view) {
    	// TUER IST GESCHLOSSEN!
    	openclose.setChecked(false);
    	doorMotor.setCurrentPosition(doorclosedstep);
    }
    
    public void opendDoor(View view) {
    	// TUER IST OFFEN!
    	openclose.setChecked(true);
    	doorMotor.setCurrentPosition(dooropendstep);
    }
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //try to connect to tf...
        connectToTF(host, port);
        openclose.setEnabled(false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
