/**
 * Main application class from codename one
 */
package com.sharefaith.churchapp;

import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;

import com.sharefaith.churchapp.model.*;
import com.sharefaith.churchapp.views.TabViews;
import com.codename1.db.Cursor;
import com.codename1.db.Row;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.util.Resources;
import com.codename1.ui.Component;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Image;
import com.codename1.ui.Tabs;

import userclasses.StateMachine;

public class ChurchApp
{
    private Form current;
    public Tabs tabComponent;
    
    public Hashtable<String,Object> childInstances;

    public void init( Object context )
    {
    	SFUtil.p( "init" );
    	
    	this.childInstances = new Hashtable<String,Object>();
    	
    	// We don't need this instance, but we do need to initialize the database. Don't delete this line.
    	ChurchAppData cad = new ChurchAppData( true );
    	
        // Pro users - uncomment this code to get crash reports sent to you automatically
    	/*
		Display.getInstance().addEdtErrorHandler(
		new ActionListener()
		{
			public void actionPerformed( ActionEvent evt )
			{
				evt.consume();
				Log.p( "Exception in AppName version " + Display.getInstance().getProperty( "AppVersion", "Unknown" ) );
				Log.p( "OS " + Display.getInstance().getPlatformName() );
				Log.p( "Error " + evt.getSource() );
				Log.p( "Current Form " + Display.getInstance().getCurrent().getName() );
				Log.e( (Throwable)evt.getSource() );
				Log.sendLog();
			}
		});*/
    }

	public void start()
	{
		SFUtil.p( "start()" );
		if( current != null )
		{
			SFUtil.p( "Resume state data" );
			current.show();
			return;
		}

		new StateMachine( "/theme" );
		
		this.initializeTabs();
		
		final ChurchApp appCaller = this;
		
		Display.getInstance().getCurrent().addOrientationListener(
		new ActionListener()
		{
			public void actionPerformed( ActionEvent evt )
			{
				String viewTag = ChurchAppData.sectionTagByLocationAndIndex( SFUtil.ICON_LOCATION_TABBAR, appCaller.tabComponent.getSelectedIndex() );
				if( !viewTag.equals( "" ) )
				{
					if( appCaller.childInstances.get( viewTag ) != null )
					{
						TabViews thisView = (TabViews)appCaller.childInstances.get( viewTag );
						thisView.rotate();
					}
				}
				Display.getInstance().getCurrent().animateLayout( 100 );
			}
		} // new ActionListener()
	
	); // current.addOrientationListener(
	} // start

	public void stop()
	{
		SFUtil.p( "Pausing" );
		current = Display.getInstance().getCurrent();
	}
    
	public void destroy() 
	{
	}
	
	/**
	 * Creates the sections in the tab bar on initial app load
	 * 
	 * @since 20140312
	 * @author costmo
	 */
	public void initializeTabs()
	{
		// read configuration options
		ChurchAppData cad = new ChurchAppData( false );

		// get the form and add the tab bar
		Form mainForm = Display.getInstance().getCurrent();
		this.tabComponent = new Tabs( Component.BOTTOM );
		this.tabComponent.setSwipeActivated( false );
		
		try
		{
			Resources res = Resources.open( "/theme.res" );
			
			int currentTabIndex = 0;
			// figure out which tabs we need to show
			String sql = new String(
					"SELECT		sf_tag "
				+ 	"FROM		ondevice_sections "
				+ 	"WHERE		ui_location = " + SFUtil.ICON_LOCATION_TABBAR + " "
				+ 	"ORDER BY	position_index"
			);
			Cursor cursor = cad.db.executeQuery( sql );
			while( cursor.next() )
			{
				Row row = cursor.getRow();
				String tag = row.getString( 0 );
				
				// Get the proper instance of the tab view and its tab bar icon files
				TabViews currentView = TabViews.getChild( tag );
				HashMap <String,String> icons = currentView.tabIconFiles();
				
				Image tabImage = res.getImage( icons.get( "normal" ) );
				Image selectedImage = res.getImage( icons.get( "selected" ) );
				
				this.tabComponent.addTab( currentView.configValues().get( "display_label" ), tabImage, currentView.contentComponent() );
				this.tabComponent.setTabSelectedIcon( currentTabIndex, selectedImage );
				
				this.childInstances.put( tag, currentView );

				currentTabIndex++;
			}
			
			
		}
		catch( IOException e )
		{
			e.printStackTrace();
			throw new RuntimeException( e.getMessage() );
		}

		this.tabComponent.setSelectedIndex( 0 );
		mainForm.addComponent( BorderLayout.CENTER, this.tabComponent );

	} // initializeTabs()
	
	/**
	 * Get information about the device
	 * 
	 * @since 20140312
	 * @author costmo
	 */
	public static HashMap<String,String> deviceInfo()
	{
		HashMap<String,String> returnValue = new HashMap<String,String>();
		
		Display currentDisplay = Display.getInstance();
		
		String orientation = new String( "portrait" );
		
		int width = currentDisplay.getDisplayWidth();
		int height = currentDisplay.getDisplayHeight();
		
		int portraitWidth = width;
		int portraitHeight = height;
		
		int landscapeWidth = width;
		int landscapeHeight = height;
		
		if( width <= height ) // We're in portrait orientation
		{
			landscapeWidth = height;
			landscapeHeight = width;
		}
		else if( width > height ) // We're in landscape orientation
		{
			portraitWidth = height;
			portraitHeight = width;
			
			orientation = new String( "landscape" );
		}
		
		returnValue.put( "os", currentDisplay.getPlatformName() );
		returnValue.put( "width", String.valueOf( width ) );
		returnValue.put( "height", String.valueOf( height ) );
		returnValue.put( "pWidth", String.valueOf( portraitWidth ) );
		returnValue.put( "pHeight", String.valueOf( portraitHeight ) );
		returnValue.put( "lWidth", String.valueOf( landscapeWidth ) );
		returnValue.put( "lHeight", String.valueOf( landscapeHeight ) );
		returnValue.put( "orientation", orientation );
		if( Display.getInstance().isTablet() )
		{
			returnValue.put( "platform", "tablet" );
		}
		else
		{
			returnValue.put( "platform", "phone" );
		}
		
		return returnValue;
	}
}
