package com.sharefaith.thesharefaithapp.adapters;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.base.SFAppData;
import com.sharefaith.thesharefaithapp.base.SFApplication;
import com.sharefaith.thesharefaithapp.base.SFConfig;
import com.sharefaith.thesharefaithapp.base.SFImageLoader;
import com.sharefaith.thesharefaithapp.base.SFUtil;
import com.sharefaith.thesharefaithapp.models.SFPostModel;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Adapter for Post items.
 */
public class SFPostAdapter extends BaseAdapter
{
	private Typeface myFace;
    private Typeface headerFace;

	private SFPostModel[] mItems;
	private BitmapFactory.Options mOptions;
	private static LimitedMapCache<String, Bitmap> mBitMapCache;
	public Context mContext;

	public SFConfig mConfig;
	private SFAppData mAppData = new SFAppData();
	private SFApplication mApplication = SFApplication.getInstance();

	/**
	 * Constructor
	 * @param context
	 * @param items
	 */
	public SFPostAdapter( Context context, SFPostModel[] items )
	{
		this.mItems = items;
		this.mContext = context;
		this.mOptions = SFUtil.commonImgOpt();
		this.mConfig = new SFConfig();

		int memMB = ((ActivityManager)context.getSystemService( Context.ACTIVITY_SERVICE )).getMemoryClass();
		this.mBitMapCache = new LimitedMapCache<String,Bitmap> ( memMB/2 );
	}

	/**
	 *
	 * @param position
	 * @param convertView
	 * @param parent
	 * @return
	 */
	@Override
	public View getView( int position, View convertView, ViewGroup parent )
	{

		ViewHolder holder;
		if (convertView == null)
		{
			LayoutInflater vi = LayoutInflater.from( this.mContext );
			int layout = mAppData.getLayout( mApplication.currentPostPosition );
			convertView = getLayout( vi, layout );
			//Yikes, the cost of inflation
			holder = new ViewHolder();

			//holder = null;
			holder.imageView = (ImageView) convertView.findViewById( R.id.imageView );
			holder.imgFile = null;//So it won't match below

			holder.titleView = (TextView) convertView.findViewById( R.id.title_textView );
			holder.excerptView = (TextView) convertView.findViewById( R.id.content_textView );
			holder.dateView = (TextView) convertView.findViewById( R.id.date_textView ); //big box
			convertView.setTag(holder);
		}
		else
		{
			holder = (ViewHolder) convertView.getTag();
		}

		SFPostModel currentObject = this.mItems[position];
		holder.position = position;

		File currentThumbnail = new File( this.mConfig.mCustomAssetPath + currentObject.mThumbnail );

		if( currentObject != null ) //Set the variable things, title and excerpt, even if not creating.
		{
			String showTitle = SFUtil.stripHtml( currentObject.mTitle ).toString();
			if( holder.titleView != null && mAppData.getIsTitleEnabled( mApplication.currentPostPosition ))
			{
				//holder.titleView.setTypeface( this.headerFace );
				//holder.titleView.setTextSize( mContext.getResources().getDimension( R.dimen.post_preview_title_font_size ) );
				holder.titleView.setText( showTitle );
				holder.titleView.setVisibility( View.VISIBLE );
			}
			else
			{
				//if image is missing show title
				if( holder.titleView != null && currentObject.mThumbnail.length() < 1 )
				{
					holder.titleView.setText( showTitle );
					holder.titleView.setVisibility( View.VISIBLE );
				}
				else
				{
					holder.titleView.setVisibility( View.GONE );
				}
			}
			//long start = System.currentTimeMillis();
			String showContent = currentObject.mExcerpt;

			//int stringEnd = (showContent.length() > 255 ) ? 255 : showContent.length();
			//showContent = showContent.substring( 0, stringEnd );
			if( holder.excerptView != null )
			{
				//holder.excerptView.setTypeface( this.myFace );
				//holder.excerptView.setTextSize( mContext.getResources().getDimension( R.dimen.post_excerpt_font_size ) );
				holder.excerptView.setText( showContent );
			}

			//Must consider cases where the view was recycled.
			if( currentObject.mThumbnail.length() > 0 && currentThumbnail.exists())//  && !currentThumbnail.equals(holder.imgFile) )
			{
				//The view has different img.
				holder.imgFile = currentThumbnail;
				String fileStr = currentThumbnail.getAbsolutePath();

				Bitmap bitmap = null;

				try {
					SFImageLoader imageLoader = new SFImageLoader();
					imageLoader.loadImage( fileStr, holder.imageView );
					//bitmap =
					//this.mBitMapCache.add(fileStr, bitmap);
				}
				catch (OutOfMemoryError e)
				{
					//((SFMainActivity)this.mContext).clearCaches();
					System.gc();
					Log.e("Error", "Error: OutOfMemory");
					bitmap = BitmapFactory.decodeFile(fileStr, this.mOptions);
				}

				//holder.imageView.setImageBitmap(bitmap);
				holder.dateView.setVisibility( View.GONE );
			}
			else
			{
				Date convertDate = new Date( currentObject.mPostDate * 1000L );
				SimpleDateFormat dateFormat = new SimpleDateFormat( "MMMM d\ny" );
				holder.imageView.setImageBitmap( null );
				holder.dateView.setText( dateFormat.format( convertDate ).toUpperCase() );
				holder.dateView.setVisibility( View.VISIBLE );
			}
			convertView.setTag(holder);
		}

		return convertView;
	}


	/**
	 *  Actions to get number of items in arraylist
	 *
	 * @since		20120106
	 */

	@Override
	public int getCount()
	{
		return this.mItems.length;
	}

	/**
	 *  Actions to get position of item
	 *
	 * @since		20120106
	 */

	@Override
	public Object getItem( int position )
	{
		return null;
	}

	/**
	 *  Actions to get item ID
	 *
	 * @since		20120106
	 */
	@Override
	public long getItemId( int id )
	{
		return 0;
	}

	/**
	 * clear the Bitmap cache
	 */
	public void clearCache()
	{
		this.mBitMapCache.clear();
	}

	/**
	 * Get the layout of the post section
	 * @param vi
	 * @param layout
	 * @return
	 */
	private View getLayout( LayoutInflater vi, int layout)
	{
		View view = null;

		if( layout == 0 )
		{
			view = vi.inflate( R.layout.sf_gamut_item, null );
		}

		else if( layout == 1 )
		{
			view = vi.inflate( R.layout.sf_nook_item, null );
		}

		else if( layout == 2 )
		{
			view = vi.inflate( R.layout.sf_reveal_item, null );
		}

		return view;
	}
}

