package com.zepchat.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import com.zepchat.app.adapters.UserListAdapter;
import com.zepchat.core.ZEPCore;
import com.zepchat.core.transport.ZEPDiscoveryTransport;
import com.zepchat.core.transport.ZEPMessagingTransport;
import com.zepchat.core.data.Message;
import com.zepchat.core.data.User;

import java.io.IOException;
import java.util.ArrayList;


public class MainActivity extends Activity implements ZEPDiscoveryTransport.UserStatusListener, ZEPMessagingTransport.MessageListener {
    private static ZEPCore core;

    private ListView userList;
    private UserListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* Turn off multicast filter */
        WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        WifiManager.MulticastLock multicastLock = wm.createMulticastLock("ZEP");
        multicastLock.acquire();

        setContentView(R.layout.activity_main);

        if(core == null) {
            SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
            if(!sharedPref.contains("localuser.alias")){
                firstTimeInit();
            }
            initCore();
        }
        else
            core.setUserStatusListener(this);
        userList = (ListView) findViewById(R.id.userList);
        adapter = new UserListAdapter(this, new ArrayList<User>());
        userList.setAdapter(adapter);

        userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(getApplicationContext(), "Click ListItem Number " + position, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, MessagingActivity.class);
                intent.putExtra("PublicKey", adapter.getItem(position).getPublicKey());
                startActivity(intent);
            }
        });
        core.setMessageListener(this);
    }

    private void firstTimeInit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Specify Alias:");

        // Set up the input
        final EditText input = new EditText(this);
        // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        builder.setView(input);

        // Set up the buttons
        final SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Save settings
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("localuser.alias", input.getText().toString());
                editor.putString("localuser.publickey", "" + (int) (Math.random() * 1000000));
                editor.commit();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.exit(0);
            }
        });

        builder.show();
    }

    private void initCore(){
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        User localUser = new User(
                sharedPref.getString("localuser.alias", null),
                sharedPref.getString("localuser.publickey", null));

        try {
            core = new ZEPCore(localUser);
            core.setUserStatusListener(this);
        }catch(IOException e){
            e.printStackTrace();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.action_scan) {
            core.scan();
            return true;
        }
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void addRemoteUser(final User user) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.add(user);
            }
        });
    }
    public void removeRemoteUser(final User user) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.remove(user);
            }
        });
    }

    @Override
    public void onResume(){
        core.setMessageListener(this);
        adapter.notifyDataSetChanged();
        userList.invalidate();
        super.onResume();
    }

    public static User getLocalUser(){
        return core.getLocalUser();
    }
    public static ZEPCore getCore(){
        return core;
    }


    @Override
    public void newMessage(Message message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
                userList.invalidate();
            }
        });
    }
}
