/* AStarDemo.java - AStarDemo activity class.
* Copyright (C) 2014 Paulo Pinto
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package org.progtools.astarsearch;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

/**
 * Application main activity.
 */
public class AStarDemo extends AppCompatActivity
{
	private MapView view;
	private Timer viewUpdater;

    // load the native part of the application
    static {
        System.loadLibrary("astardemo");
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Display display = getWindowManager().getDefaultDisplay();
        Point outSize = new Point();
        display.getSize(outSize);
        
        Log.d(this.getClass().getName(), String.format("%s", outSize.toString()));
        
        view = new MapView(this, outSize.x, outSize.y);
        registerForContextMenu (view);
        setContentView(view);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_open:
            	openFileRequest();
                return true;
            case R.id.action_run:
            	//view.startSearch(20, 20, 60, 60);
                view.startSearch();
                return true;
            case R.id.action_clear:
            	view.clear();
            	return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onResume() {
     super.onResume();
     
     // sets up a timer to deliver updates to the main view
     viewUpdater = new Timer();
     viewUpdater.schedule(new TimerTask() {
      @Override
      public void run() {
       runOnUiThread(new Runnable() {
        public void run() {
        	view.invalidate();
        }
       });
      }
     }, 0, 100); // updates every second
    }   
    
    @Override
    public void onPause() {
    	if (viewUpdater != null) {
    		viewUpdater.cancel();
    	}
    	super.onPause();
    }    
    
    // Intent request ID.
    final int REQUEST_CODE_LOAD_MAP = 1;
    
    /**
     * Asks the user to select a file with a map file.
     * Based on some information in StackOverflow, on how to make
     * use of Samsung file pickers, when run on such devices.
     */
    private void openFileRequest()
    {
    	String mimeType = "*/*";
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(mimeType);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        // special intent for the Samsung file manager
        Intent samsungIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
        samsungIntent.putExtra("CONTENT_TYPE", mimeType); 
        samsungIntent.addCategory(Intent.CATEGORY_DEFAULT);

        Intent chooserIntent;
        if (getPackageManager().resolveActivity(samsungIntent, 0) != null){
            // it is device with samsung file manager
            chooserIntent = Intent.createChooser(samsungIntent, "Open file");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
        }
        else {
            chooserIntent = Intent.createChooser(intent, "Open file");
        }

        try {
            startActivityForResult(chooserIntent, REQUEST_CODE_LOAD_MAP);
        } catch (ActivityNotFoundException ex) {
            Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * Takes care of the opening the file selected by the user.
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_LOAD_MAP && resultCode == RESULT_OK) {
                Uri imageUri= data.getData();
                Log.d("image selected path", imageUri.getPath());
                if (!view.loadMap(imageUri.getPath())) {
                	Toast.makeText(getApplicationContext(), "Failed to load map!", Toast.LENGTH_SHORT).show();
                }
        }
    }
}