package com.sharefaith.thesharefaithapp.models;

import com.appideas.base.AiDb;
import com.appideas.base.AiSTr;
import com.sharefaith.thesharefaithapp.base.SFAppData;
import com.sharefaith.thesharefaithapp.base.SFApplication;
import com.sharefaith.thesharefaithapp.base.SFConfig;
import com.sharefaith.thesharefaithapp.base.SFCustomDownload;
import com.sharefaith.thesharefaithapp.base.SFUtil;

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

/**
 * Created by Sharefaith1 on 2014-10-23.
 */
public class SFPostModel
{
	/**
	 * This object's database ID
	 */
	public int mId;

	/**
	 * This the title
	 */
	public String mTitle;

	/**
	 * This content
	 */
	public String mContent;

	/**
	 * This excerpt of the content
	 */
	public String mExcerpt;

	/**
	 * This object's database tag
	 */
	public String mSfTag;

	/**
	 * This object's thumbnail location
	 */
	public String mThumbnail;

	/**
	 * This object's visible label
	 */
	public int mPostDate;

	/**
	 * The user's current theme (for piecing together the icon location)
	 */
	public String mShowDate;

	/**
	 * Instance of the database
	 */
	private AiDb mDb;

	/**
	 * This object's Sync Object OD
	 */
	public int mExternalId;

	/**
	 * This object's original thumbnail URL
	 */
	public String mThumbnailOrigin;

	public String mIncludedIn;

	public String mCats;

	public int mWpId;

	/**
	 * Class constructor
	 *
	 * @since		20141021
	 */
	public SFPostModel( int id )
	{
		if( id < 0 )
		{
			id = 0;
		}

		this.mId = id;
		this.mSfTag = "posts";

		this.mDb = SFApplication.getInstance().getDb();
		this.refreshMembers();
	}

	public SFPostModel()
	{
		this( 0 );
	}

	/**
	 * Refresh member variables for a specific menu item from the datasource
	 *
	 * @since		20141021
	 */
	public void refreshMembers()
	{

		this.mTitle = "";
		this.mContent = "";
		this.mExcerpt = "";
		this.mThumbnail = "";
		this.mPostDate = 0;
		this.mShowDate = "";
		this.mExternalId = 0;
		this.mThumbnailOrigin = "";
		this.mIncludedIn = "";
		this.mCats = "";
		this.mWpId = 0;

		if( this.mDb == null )
		{
			this.mDb = SFApplication.getInstance().getDb();
		}

		String sql =	"SELECT     COALESCE( content, '' ) as content " +
						"FROM       section_content " +
						"WHERE      id = " + this.mId;
		String[][] result = this.mDb.query( sql );
		for( int i = 0; i < result.length; i++ )
		{
			this.mTitle =  AiSTr.denullifyString( result[ i ][ 0 ] );
		}

		sql =	"SELECT     meta_key, meta_value " +
				"FROM       section_content_meta " +
				"WHERE      section_content_id = " + this.mId;
		result = this.mDb.query( sql );
		for( int i = 0; i < result.length; i++ )
		{
			String key = AiSTr.denullifyString( result[i][0] );
			String value = AiSTr.denullifyString( result[i][1] );

			if( key.equals( "thumbnail" ) )
			{
				SFConfig config = new SFConfig();

				if( value.length() > 0 )
				{
					this.mThumbnail = value;
				}
				else
				{
					this.mThumbnail = "";
				}
			}
			else if( key.equals( "postdate" ) )
			{
				this.mPostDate = AiSTr.denullifyInt( value );

				Date convertDate = new Date( this.mPostDate * 1000L );
				SimpleDateFormat dateFormat = new SimpleDateFormat( "MMMM d\nyyyy" );
				this.mShowDate = dateFormat.format( convertDate );
			}
			else if( key.equals( "externalid" ) )
			{
				this.mExternalId = AiSTr.denullifyInt( value );
			}
			else if( key.equals( "thumbnailorigin" ) )
			{
				this.mThumbnailOrigin = value;
			}
			else if( key.equals( "content" ) )
			{
				this.mContent = value;
				if( SFUtil.stripHtml(value).length() > 100 )
				{
					this.mExcerpt = SFUtil.stripHtml(value).toString().substring( 0, 100 );
					//Log.d("mtag", "Excerpt = " + mExcerpt);
				}
				else
				{
					this.mExcerpt = SFUtil.stripHtml(value).toString();
				}
			}
			else if( key.equals( "includedIn" ) )
			{
				this.mIncludedIn = value;
			}
			else if( key.equals( "cats" ) )
			{
				this.mCats = value;
			}
			else if( key.equals( "wpid" ) )
			{
				this.mWpId = AiSTr.denullifyInt( value );
			}

		}
	}

	/**
	 * Get instances of all menu items for the main navigation menu
	 *
	 * @since		20141021
	 */
	public static SFPostModel[] getAll()
	{
		Integer[] idArray = SFPostModel.getAllIds();
		SFPostModel[] items = new SFPostModel[idArray.length];

		for( int i = 0; i < idArray.length; i++ )
		{
			items[i] = new SFPostModel( idArray[i] );
		}

		return items;
	}

	/**
	 * Get the ID for all instances that should appear in the nav menu
	 *
	 * @since		20141021
	 */
	public static Integer[] getAllIds()
	{
		AiDb db = SFApplication.getInstance().getDb();
		SFPostModel baseModel = new SFPostModel();

		String sql =	"SELECT     id " +
						"FROM       section_content " +
						"WHERE      ondevice_section_id = " +
						"			(SELECT id FROM ondevice_sections WHERE sf_tag = '" + baseModel.mSfTag + "') AND " +
						"			parent_id = 0 " +
						"ORDER BY	position_index DESC";
		String[][] result = db.query( sql );
		Integer[] returnValue = new Integer[result.length];
		for( int i = 0; i < result.length; i++ )
		{
			returnValue[i] =  AiSTr.denullifyInt( result[ i ][ 0 ] );
		}

		return returnValue;
	}

	/**
	 * Get a model object from its external object ID
	 *
	 */
	public static SFPostModel objectFromExternalId( int externalId )
	{
		//Log.d("mTag","hit objectFromExternalID for: " + externalId);
		SFPostModel model = new SFPostModel( 0 );

		AiDb db = SFApplication.getInstance().getDb();

		String sql =	"SELECT     section_content.id AS id " +
				"FROM       section_content, section_content_meta " +
				"WHERE      section_content.ondevice_section_id = " +
				"				(SELECT id FROM ondevice_sections WHERE sf_tag = '" + model.mSfTag + "') AND " +
				"			section_content.parent_id = 0 AND " +
				"			section_content_meta.section_content_id = section_content.id AND " +
				"			section_content_meta.meta_key = 'externalid' AND " +
				"			section_content_meta.meta_value = " + externalId;
		String[][] result = db.query( sql );
		for( int i = 0; i < result.length; i++ )
		{
			int id =  AiSTr.denullifyInt( result[ i ][ 0 ] );
			//Log.d("mTag", "id result from query = " +id);
			model = new SFPostModel( id );
		}

		return model;
	}

	/**
	 *
	 * @param replaceThumbnail
	 */
	public void saveMembers( boolean replaceThumbnail )
	{
		//Log.d( "mTag", "Hit save member on post " + this.mId );
		boolean isNew = false;

		if( this.mId == 0 )
		{
			isNew = true;
			this.mId = this.mDb.insertBlank( "section_content", "id" );
		}

		String sql =
				"UPDATE		section_content " +
				"SET		content = '" + AiSTr.dbEscape( this.mTitle ) + "', " +
						"	position_index = " + this.mPostDate + ", " +
				"			ondevice_section_id = " +
				"				( SELECT id FROM ondevice_sections WHERE sf_tag = 'posts' ) " +
				"WHERE		id = " + this.mId;
		this.mDb.noReturnQuery( sql );

		String keys[] = { "postdate", "content", "thumbnail", "thumbnailorigin", "externalid", "includedIn", "cats", "wpid" };

		if( isNew )
		{
			for( int i = 0; i < keys.length; i++ )
			{
				String prepSql =
						"INSERT INTO	section_content_meta " +
						"				( section_content_id, meta_key, meta_value ) " +
						"VALUES			( " + this.mId + ", '" + keys[i] + "', '' )";
				this.mDb.noReturnQuery( prepSql );
			}
		}

		HashMap<String,String> input = new HashMap<String,String>();
		input.put( "postdate", String.valueOf( this.mPostDate ) );
		input.put( "content", this.mContent );
		input.put( "thumbnail", this.mThumbnail );
		input.put( "thumbnailorigin", this.mThumbnailOrigin );
		input.put( "externalid", String.valueOf( this.mExternalId ) );
		input.put( "includedIn", this.mIncludedIn );
		input.put( "cats", this.mCats );
		input.put( "wpid", Integer.toString( this.mWpId ) );

		for( HashMap.Entry<String,String> map : input.entrySet() )
		{
			sql =
					"UPDATE		section_content_meta " +
					"SET		meta_value = '" + AiSTr.dbEscape( AiSTr.denullifyString( map.getValue() ) ) + "' " +
					"WHERE		section_content_id = " + this.mId + " AND " +
					"			meta_key = '" + map.getKey() + "' ";
			this.mDb.noReturnQuery( sql );
		}

		if( replaceThumbnail )
		{
			SFCustomDownload download = new SFCustomDownload();
			String filename = "";
			try
			{
				filename = download.downloadFile( this.mThumbnailOrigin );
			}
			catch( Exception e )
			{
				// If we got an exception, we just record empty file
				filename = "";
			}

			sql =
					"UPDATE		section_content_meta " +
					"SET		meta_value = '" + filename + "' " +
					"WHERE		section_content_id = " + this.mId + " AND " +
					"			meta_key = 'thumbnail' ";
			this.mDb.noReturnQuery( sql );

		} // if( replaceThumbnail )

		//update post_to_section
		sql =
				" DELETE FROM post_to_section " +
						" WHERE post_section_content_id = " + this.mId;
		this.mDb.noReturnQuery( sql );

		Integer[] indludedIn = SFApplication.getInstance().parseIncludedIn( this.mIncludedIn );

		for( int i = 0; i < indludedIn.length; i ++ )
		{
			sql =
					" INSERT INTO post_to_section " +
							" ( post_section_content_id, ondevice_section_id ) " +
							" VALUES ( " + this.mId + ", (SELECT id FROM ondevice_sections WHERE external_id = " + indludedIn[i] + ") )";
			this.mDb.noReturnQuery( sql );
		}

	} // public void saveMembers( boolean replaceThumbnail )

	/**
	 *
	 */
	public static void setOrder()
	{
		AiDb db = SFApplication.getInstance().getDb();

		SFPostModel[] models = SFPostModel.getAll();

		for( int i = 0; i < models.length; i++ )
		{
			SFPostModel model = models[i];

			int postDate = 0;
			String sql =
					"SELECT     meta_value " +
					"FROM       section_content_meta " +
					"WHERE      section_content_id = " + model.mId + " AND " +
					"			meta_key = 'postdate'";
			String[][] result = db.query( sql );
			for( int j = 0; j < result.length; j++ )
			{
				postDate =  AiSTr.denullifyInt( result[ j ][ 0 ] );
			}

			sql =
					"UPDATE		section_content " +
					"SET		position_index = " + postDate + " " +
					"WHERE		id = " + model.mId;
			db.noReturnQuery( sql );
		}
	}

	/**
	 *
	 */
	public void remove()
	{
		SFConfig config = new SFConfig();

		if( this.mThumbnail.length() > 0 )
		{
			String thumbnailPath = config.mCustomAssetPath + this.mThumbnail;
			File file = new File( thumbnailPath );
			file.delete();
		}

		String sql =
				"DELETE FROM	section_content_meta " +
				"WHERE			section_content_id = " + this.mId;
		this.mDb.noReturnQuery( sql );

		sql =
				"DELETE FROM	section_content " +
				"WHERE			id = " + this.mId;
		this.mDb.noReturnQuery( sql );

		sql =
				"DELETE FROM	post_to_section " +
						"WHERE			post_section_content_id = " + this.mId;
		this.mDb.noReturnQuery( sql );
	}

	/**
	 *
	 */
	public void saveHashValue()
	{
		SFAppData appData = new SFAppData();
		String returnvalue = calculateHashValue();

		String sql =
				"DELETE FROM sync_objects " +
				"WHERE sync_object_id = " + mExternalId;
		mDb.noReturnQuery( sql );

		sql =
				"INSERT INTO sync_objects " +
				"( sync_object_id, hash_value, object_type ) " +
				"VALUES ( " + mExternalId + ", '" + returnvalue + "', 'post' )"
		;
		mDb.noReturnQuery( sql );

		appData.hashImage( mExternalId );
	}

	/**
	 *
	 * @return
	 */
	public String calculateHashValue()
	{
		String hashContent = mContent.trim();
		String stingToHash = mTitle + hashContent + mPostDate + mThumbnailOrigin + mIncludedIn;

		return SFUtil.md5( stingToHash );
	}
}
