package com.utbm.lo53.whereami;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;


public class Positioning extends AppCompatActivity
{
    ImageView pin;
    String address;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_positioning);
        pin = (ImageView) findViewById(R.id.dot);
        pin.setVisibility(View.INVISIBLE);
    }
    public void onClickLocate (View view)
    {
        WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        if(wifiManager.isWifiEnabled())
        {
            // WIFI ALREADY ENABLED. GRAB THE MAC ADDRESS HERE
            WifiInfo info = wifiManager.getConnectionInfo();
            address = info.getMacAddress();
        }
        else
        {
            // ENABLE THE WIFI FIRST
            wifiManager.setWifiEnabled(true);
            // WIFI IS NOW ENABLED. GRAB THE MAC ADDRESS HERE
            WifiInfo info = wifiManager.getConnectionInfo();
            address = info.getMacAddress();
        }
        //check the preferences to get ip/port
        SharedPreferences sharedPref = getSharedPreferences("preferences", MODE_PRIVATE);
        String ip_address = sharedPref.getString("ip_address", "");
        String port_number = sharedPref.getString("port_number", "");
        if (ip_address == "" || port_number == "")
        {
            Toast.makeText(getApplicationContext(),"You need to set Server IP/Port", Toast.LENGTH_LONG).show();
            //open Preference activity
            Intent intent = new Intent(this, Preference.class);
            startActivity(intent);
        }
        else
        {
            // send request to server
            String position = Connection.command(ip_address, port_number, "getPosition&mac="+ address);
                String s[] = position.split(";");
            if (s.length == 2)
            {
                //set Pin x,y
                pin.setX(Integer.parseInt(s[0]));
                pin.setY(Integer.parseInt(s[1]));
                pin.setVisibility(View.VISIBLE);
                pin.bringToFront();
            }
            else
            {
                Toast.makeText(getApplicationContext(),"Failed to get position\nPlease check your connection settings", Toast.LENGTH_LONG).show();

            }
        }
    }
}
