package fishrungames.kobserver;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import fishrungames.kobserver.JniWrapper;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;

import android.os.Bundle;

import android.view.View;


import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class MapActivity extends Activity
{
	
	ArrayAdapter<String> spinnerAdapter;
	
	public Timer mapUpdateTimer;
	
	@Override
	protected void onCreate(Bundle icicle)
	{

		super.onCreate(icicle);

		setContentView(R.layout.map_layout);	
		
		Button backbtn = (Button) findViewById(R.id.backButton_map);
		backbtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), MainMenuActivity.class);
                startActivityForResult(myIntent, 0);
            }
        });
		
		Spinner mapModeSpinner = (Spinner) findViewById(R.id.mapModeSpinner);
		
		ArrayList<String> strings = 
		        new ArrayList<String>(Arrays.asList("Общая карта", "Карта тревоги"));
		
		spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, strings);

		mapModeSpinner.setAdapter(spinnerAdapter);
		
		WebView webView = (WebView) findViewById(R.id.webView);
		
		mapModeSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener(webView));
		
		
		String htmlCode = new String();
		
		try {
	        Resources res = getResources();
	        InputStream in_s = res.openRawResource(R.raw.script);

	        byte[] b = new byte[in_s.available()];
	        in_s.read(b);
	        htmlCode = new String(b);
	    } catch (Exception e) {
	         e.printStackTrace();
	    }

		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setDomStorageEnabled(true);
		
		webView.setWebChromeClient(new WebChromeClient());
		
		htmlCode = htmlCode.replace("%", "&#37;");  
		
		float lon = JniWrapper.GetMapCenterPosX();
		float lat = JniWrapper.GetMapCenterPosY();
		int zoom = JniWrapper.GetMapCenterZoom();
		htmlCode = htmlCode.replace("__LON__", Float.toString(lon));
		htmlCode = htmlCode.replace("__LAT__", Float.toString(lat));
		htmlCode = htmlCode.replace("__ZOOM__", Integer.toString(zoom));
		
		webView.loadData(htmlCode, "text/html", "UTF-8");
		
		mapUpdateTimer = new Timer();
    	
		mapUpdateTimer.schedule(new MapUpdateTimerTask(), 0, 1000);
		
		//webView.loadUrl("javascript:(function() { ActivateSelectControl();})()");
		

	}
	
	public class MyOnItemSelectedListener implements OnItemSelectedListener {

		public WebView webView = null;
		
		
		MyOnItemSelectedListener(WebView selectWebView)
		{
			webView = selectWebView;
		}
		
        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
          
        	if (pos == 0)
        	{
        		JniWrapper.ChangeMapType(0);
        		webView.loadUrl("javascript:(function() { DeactivateSelectControl();})()");
        	}
        	else
        	{
        		JniWrapper.ChangeMapType(1);
        		webView.loadUrl("javascript:(function() { ActivateSelectControl();})()");
        	}
        }
        	

        public void onNothingSelected(AdapterView<?> parent) {
          // Do nothing.
        }
    }

	
	
	class MapUpdateTimerTask extends TimerTask
	{
		
		@Override
		public void run()
		{
			WebView webView = (WebView) findViewById(R.id.webView);
			webView.loadUrl("javascript:(function() { Clear();})()");
			
			int userCount = JniWrapper.GetNumberOfUsers();
			
			for (int i=0; i<userCount; i++)
			{
				String descr = JniWrapper.GetUserDescription(i);
				String code = String.format("javascript:(function() { AddMarkerWithPopup(%f, %f, %d, '%s');})()", 
						JniWrapper.GetUserPosX(i),
						JniWrapper.GetUserPosY(i),
						JniWrapper.GetUserMapState(i),
						descr);
				
				webView.loadUrl(code);
				
			}
					
			//webView.loadUrl("javascript:(function() { AddMarkerWithPopup(30.2158, 60.0052, 1, 'lolwut');})()");
			
			
		}
	}
	
}