<?php
/**
 * @brief		Background Task
 * @author		<a href='https://www.invisioncommunity.com'>Invision Power Services, Inc.</a>
 * @copyright	(c) Invision Power Services, Inc.
 * @license		https://www.invisioncommunity.com/legal/standards/
 * @package		Invision Community
 * @subpackage	Chatbox+
 * @since		05 Mar 2019
 */

namespace IPS\chatbox\extensions\core\Queue;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * Background Task
 */
class _deleteMsg
{

	/**
	 * @brief Number of topics to build per cycle
	 */
	public $rebuild = 20;
	
	/**
	 * Parse data before queuing
	 *
	 * @param	array	$data
	 * @return	array
	 */
	public function preQueueData( $data )
	{
		# For messages in conversations
		if ( $data['convo'] != null && $data['convo'] >= 0 )
		{
			$table = 'chatbox_conversations_posts';
			
			if ( $data['convo'] > 0 )
			{
				$where[] = array( 'chat_con=?', $data['convo'] ); 
			}
			if ( $data['user'] )
			{
				$where[] = array( 'chat_member_id=?', $data['user'] ); 
			}
			if ( $data['where'] )
			{
				$where[] = $data['where'];
			}
		}
		
		# For messages in rooms
		else
		{
			$table = 'chatbox_room_posts';
			
			if ( $data['room'] > 0 )
			{
				$where[] = array( '( chat_room=? OR FIND_IN_SET( ?, chat_in_multiple_rooms ) )', $data['room'], $data['room'] ); 
			}
			if ( $data['user'] )
			{
				$key = explode( "@", $data['user'] );
				
				if ( $key[0] == 'user' )
				{
					$where[] = array( 'chat_member_id=?', $key[1] ); 
				}
				else
				{
					$where[] = array( 'chat_guestName=?', $key[1] ); 
				}
			}
			if ( $data['where'] )
			{
				$where[] = $data['where'];
			}			
		}
		
		# Count
		try
		{
			$data['count']		= \IPS\Db::i()->select( 'MAX( chat_id )', $table, $where )->first();
			$data['realCount']	= \IPS\Db::i()->select( 'COUNT(*)', $table, $where )->first();
		}
		catch( \Exception $ex )
		{
			return NULL;
		}
		
		if( $data['count'] == 0 or $data['realCount'] == 0 )
		{
			return NULL;
		}

		$data['indexed'] = 0;
		
		return $data;
	}

	/**
	 * Run Background Task
	 *
	 * @param	mixed						$data	Data as it was passed to \IPS\Task::queue()
	 * @param	int							$offset	Offset
	 * @return	int							New offset
	 * @throws	\IPS\Task\Queue\OutOfRangeException	Indicates offset doesn't exist and thus task is complete
	 */
	public function run( $data, $offset )
	{
		$count = 0;
		
		# Delete messages in conversations
		if ( $data['convo'] > 0 )
		{
			if ( $data['convo'] > 0 )
			{
				$where[] = array( 'chat_con=?', $data['convo'] ); 
			}
			if ( $data['user'] )
			{
				$where[] = array( 'chat_member_id=?', $data['user'] ); 
			}
			if ( $data['where'] )
			{
				$where[] = $data['where'];
			}			
			$select = \IPS\Db::i()->select( '*', 'chatbox_conversations_posts', $where, 'chat_id', array( 0, $this->rebuild ) );
			
			foreach( $select as $chat )
			{
				// $obj = \IPS\chatbox\Member\Post::constructFromData( $chat );
				// $obj->delete();
				
				\IPS\Application::load('chatbox')->deleteFilesFromMSG( 'con', $chat['chat_id'] );
				\IPS\File::unclaimAttachments( 'chatbox_conMSG', $chat['chat_id'] );
				\IPS\Db::i()->delete( 'chatbox_conversations_posts', array( 'chat_id=?', $chat['chat_id'] ) );
					
				$data['indexed']++;
				$last = $chat['chat_id'];				
			}			
		}
		
		# Delete messages in rooms
		else
		{
			if ( $data['room'] > 0 )
			{
				$where[] = array( '( chat_room=? OR FIND_IN_SET( ?, chat_in_multiple_rooms ) )', $data['room'], $data['room'] ); 
			}
			if ( $data['user'] )
			{
				$key = explode( "@", $data['user'] );
				$where[] = ( $key[0] == 'user' ) ? array( 'chat_member_id=?', $key[1] ) : array( 'chat_guestName=?', $key[1] ); 
			}
			if ( $data['where'] )
			{
				$where[] = $data['where'];
			}			
			$select = \IPS\Db::i()->select( '*', 'chatbox_room_posts', $where, 'chat_id', array( 0, $this->rebuild ) );
			
			foreach( $select as $chat )
			{
				if ( $chat['chat_room'] > 0 )
				{
					// $obj = \IPS\chatbox\Rooms\Chat::constructFromData( $chat );
					// $obj->delete();
					
					\IPS\Application::load('chatbox')->deleteFilesFromMSG( 'room', $chat['chat_id'] );
					\IPS\File::unclaimAttachments( 'chatbox_roomMSG', $chat['chat_id'] );
					\IPS\Db::i()->delete( 'chatbox_room_posts', array( 'chat_id=?', $chat['chat_id'] ) );	
				}
				else
				{
					if ( $chat['chat_in_multiple_rooms'] === (string) $data['room'] )
					{
						\IPS\Application::load('chatbox')->deleteFilesFromMSG( 'room', $chat['chat_id'] );
						\IPS\File::unclaimAttachments( 'chatbox_roomMSG', $chat['chat_id'] );
						\IPS\Db::i()->delete( 'chatbox_room_posts', array( 'chat_id=?', $chat['chat_id'] ) );				
					}
					else
					{
						$r = explode( ",", $chat['chat_in_multiple_rooms'] );
						$rooms = array_diff( $r, [ $data['room'] ] );
						\IPS\Db::i()->update( 'chatbox_room_posts', array( 'chat_in_multiple_rooms' => implode( ",", $rooms ) ), array( 'chat_id=?', $chat['chat_id'] ) );
					}
				}
				
				$data['indexed']++;
				$last = $chat['chat_id'];				
			}
		}
		
		# No last
		if( $last === NULL )
		{
			throw new \IPS\Task\Queue\OutOfRangeException;
		}
		
		# Done
		return $last;
	}
	
	/**
	 * Get Progress
	 *
	 * @param	mixed					$data	Data as it was passed to \IPS\Task::queue()
	 * @param	int						$offset	Offset
	 * @return	array( 'text' => 'Doing something...', 'complete' => 50 )	Text explaining task and percentage complete
	 * @throws	\OutOfRangeException	Indicates offset doesn't exist and thus task is complete
	 */
	public function getProgress( $data, $offset )
	{
		return array( 'text' => \IPS\Member::loggedIn()->language()->addToStack('chatbox_queue_delete_msg'), 'complete' => ( $data['realCount'] * $data['indexed'] ) > 0 ? round( ( $data['realCount'] * $data['indexed'] ) * 100, 2 ) : 0 );
	}

	/**
	 * Perform post-completion processing
	 *
	 * @param	array	$data
	 * @return	void
	 */
	public function postComplete( $data )
	{
		if ( !$data['convo'] )
		{
			unset( \IPS\Data\Store::i()->chatbox_rooms_data );
		}
	}
}