CREATE PROCEDURE [dbo].[sp_GetSurfaceData]
	@SurfaceID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

		DECLARE @cols AS NVARCHAR(MAX),
		@query  AS NVARCHAR(MAX)

		select @cols = STUFF((SELECT ',' + QUOTENAME(surfaceFieldName) 
                    from pal_SurfaceField sf where sf.surfaceFieldTypeId <> 1 AND sf.surfaceFieldTypeId <> 2 and sf.surfaceId = @SurfaceID
                    group by sf.surfaceFieldName, sf.recId
                    order by sf.surfaceFieldName
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

		set @query = N'SELECT
					*
					FROM
					(
						SELECT  item.recId AS [itemID], item.isActive, 
						field.surfaceId,
						ISNULL(CASE field.surfaceFieldTypeId
								WHEN 3 Then CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))
								WHEN 4 Then CAST(data.surfaceFieldValueNum AS VARCHAR(MAX))
								WHEN 5 THEN CAST(data.surfaceFieldValueDecimal AS VARCHAR(MAX))
								WHEN 6 THEN  
										CASE WHEN LEN(CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))) > 0
											THEN CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))
											ELSE (select display from pal_SurfaceLookup where pal_SurfaceLookup.recId = data.surfaceFieldLookupID)
											END
								WHEN 7 Then CASE WHEN field.surfaceDateTypeId = 2 THEN DATENAME(MONTH, data.surfaceFieldValueDate) + '' '' + CONVERT(VARCHAR,DATEPART(YYYY, data.surfaceFieldValueDate))
											ELSE CONVERT(VARCHAR, data.surfaceFieldValueDate, 111) /* yyyy/mm/dd*/ END
								WHEN 8 THEN CAST(data.surfaceFieldValueBool AS VARCHAR(MAX))									 
								WHEN 9 THEN  
										CASE WHEN LEN(CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))) > 0
											THEN CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))
											ELSE (select display from pal_SurfaceLookup where pal_SurfaceLookup.recId = data.surfaceFieldLookupID)
											END
								WHEN 14 THEN
									CASE WHEN field.actionType = 8
									THEN CASE field.[action]
										WHEN 12
											THEN CAST(dbo.fn_GetSurfaceFieldAggregateAverage(item.recId,field.actionValue,0) AS VARCHAR(MAX))
										WHEN 14
											THEN CASE WHEN field.controlledValue = ''75'' THEN CAST(dbo.fn_GetSurfaceFieldAggregateDistinctionCount(item.recId,field.actionValue, 0) AS VARCHAR(MAX)) 
												ELSE CAST(dbo.fn_GetSurfaceFieldAggregateDistinctionCount(item.recId,field.actionValue, DEFAULT) AS VARCHAR(MAX)) END
										WHEN 15
											THEN CAST(dbo.fn_GetSurfaceFieldAggregateSum(item.recId,field.actionValue) AS VARCHAR(MAX))
										WHEN 16
											THEN CAST(dbo.fn_GetSurfaceFieldAggregateDIFF(item.recId,field.actionValue) AS VARCHAR(MAX))
										WHEN 17
											THEN CAST(dbo.fn_GetSurfaceFieldAggregateFailed(item.recId,field.actionValue) AS VARCHAR(MAX))
										WHEN 18
											THEN CAST(dbo.fn_GetSurfaceFieldAggregatePassed(item.recId,field.actionValue) AS VARCHAR(MAX))
										END
									WHEN field.actionType = 1
									THEN CASE WHEN field.[action] = 13
										THEN

										CASE WHEN ( CAST((SELECT	CASE F.surfaceFieldTypeId
														WHEN 4 THEN D.surfaceFieldValueNum 
														WHEN 5 THEN D.surfaceFieldValueDecimal  
														WHEN 14 THEN CASE WHEN F.actionType = 8
																	THEN CASE WHEN F.[action] = 12
																		THEN dbo.fn_GetSurfaceFieldAggregateAverage(D.surfaceItemId,F.actionValue,0) 
																		END 
																	END
																END
												FROM	pal_Surface S
														JOIN pal_SurfaceField F
															ON F.surfaceId = S.recId
															AND S.recId = ' + CAST(@SurfaceID AS VARCHAR(MAX)) + '
														JOIN pal_SurfaceFieldData D 
															ON D.surfaceFieldID = F.recId 
															AND D.surfaceId = F.surfaceId
															AND D.surfaceItemID = item.recId
												WHERE	F.recId = field.actionSource) AS VARCHAR(100)) IS NULL)
											THEN '''' 
											ELSE
											CAST(DENSE_RANK() OVER
											(PARTITION BY
												(
												SELECT STUFF((SELECT '','' + D2.surfaceFieldValueChar
                                                FROM pal_SurfaceField F2  
                                                JOIN pal_SurfaceFieldData D2 ON D2.surfaceFieldID = F2.recId AND D2.surfaceItemId = item.recId
                                                WHERE F2.surfaceId = field.surfaceId 
                                                AND F2.recId IN (SELECT CASE WHEN ISNUMERIC(splitdata) = 1 THEN splitdata ELSE 0 END FROM dbo.SplitString(field.actionValue, ''|''))
                                                FOR XML PATH(''''), TYPE
                                                        ).value(''.'', ''VARCHAR(MAX)'') 
                                                        ,1,1,'''')
												)	
											ORDER BY 
												(SELECT	CASE F.surfaceFieldTypeId
														WHEN 4 THEN D.surfaceFieldValueNum 
														WHEN 5 THEN D.surfaceFieldValueDecimal  
														WHEN 14 THEN CASE WHEN F.actionType = 8
																	THEN CASE WHEN F.[action] = 12
																		THEN dbo.fn_GetSurfaceFieldAggregateAverage(D.surfaceItemId,F.actionValue,0) 
																		END 
																	END
																END
												FROM	pal_Surface S
														JOIN pal_SurfaceField F
															ON F.surfaceId = S.recId
															AND S.recId = ' + CAST(@SurfaceID AS VARCHAR(MAX)) + '
														JOIN pal_SurfaceFieldData D 
															ON D.surfaceFieldID = F.recId 
															AND D.surfaceId = F.surfaceId
															AND D.surfaceItemID = item.recId
												WHERE	F.recId = field.actionSource)	
											DESC)
											AS VARCHAR(MAX))	
											--CAST(dbo.fn_GetSurfaceFieldItemRanking(' + CAST(@SurfaceID AS VARCHAR(MAX)) + ',item.recId,field.recId) AS VARCHAR(MAX))	
											END			
										WHEN field.[action] = 2 --age
											THEN (SELECT CAST((CONVERT(int,CONVERT(char(8),GETDATE(),112))-CONVERT(char(8),DD.surfaceFieldValueDate,112))/10000  AS VARCHAR(10))
												FROM	pal_SurfaceFieldData DD
												WHERE	DD.surfaceItemId = item.recId
														AND DD.surfaceFieldID = field.actionSource)	
										WHEN field.[action] = 7 -- divide
											THEN CAST(dbo.fn_GetSurfaceCalculationDivide(item.recId,field.actionSource,field.actionValue) AS VARCHAR(MAX))
										WHEN field.[action] = 20 -- percentage
											THEN CAST(dbo.fn_GetSurfaceCalculationPercentage(item.recId,field.actionSource,field.actionValue) AS VARCHAR(MAX))
										ELSE 
											CASE WHEN LEN(CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))) > 0
												THEN CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))
												ELSE CASE WHEN data.surfaceFieldValueDecimal > 0
														THEN CAST(data.surfaceFieldValueDecimal AS VARCHAR(MAX))
													END
											END
										END
									ELSE
									CASE WHEN LEN(CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))) > 0
										THEN CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))
										ELSE CASE WHEN data.surfaceFieldValueDecimal > 0
												THEN CAST(data.surfaceFieldValueDecimal AS VARCHAR(MAX))
												END
											END
									END
								WHEN 15 THEN  convert(VARCHAR,data.surfaceFieldValueTime,  114) /* hh:mm:ss:mmm(24h)*/									 
								WHEN 20 Then CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))
								WHEN 25 Then CAST(data.surfaceFieldValueChar AS VARCHAR(MAX))
								WHEN 26 THEN 
									STUFF((
										SELECT CAST('', '' + display  AS VARCHAR(MAX))
										FROM pal_SurfaceLookup 
										WHERE recId IN (select SUBSTRING(splitdata, 0, CHARINDEX(''~R~'', splitdata)) from dbo.SplitString(data.surfaceFieldValueChar, ''~|~''))
										FOR XML PATH (''''))
										, 1, 2, '''') 
								WHEN 29 THEN
									CASE field.relationalSurface 
										WHEN ''date'' THEN (CASE WHEN YEAR(item.dateUpdated) = 1900 THEN CONVERT(VARCHAR, item.dateCreated, 120) ELSE CONVERT(VARCHAR, item.dateCreated, 120) + '' (last updated on '' + CONVERT(VARCHAR, item.dateUpdated, 120) + '')'' END)
										WHEN ''user'' THEN 
											CASE WHEN item.updatedBy = 0 THEN (SELECT userDisplay FROM [Framework_EVOL-1].dbo.pal_User WHERE recId =  item.createdBy) 
											ELSE (SELECT userDisplay FROM [Framework_EVOL-1].dbo.pal_User WHERE recId =  item.createdBy) + '' (last updated by '' + (SELECT userDisplay FROM [Framework_EVOL-1].dbo.pal_User WHERE recId =  item.updatedBy) + '')'' 
											END
									END
								WHEN 30 THEN 
									STUFF((
										SELECT CAST(''; '' + display  AS VARCHAR(MAX))
										FROM pal_SurfaceLookup 
										WHERE recId IN (select splitdata from dbo.SplitString(data.surfaceFieldValueChar, '',''))
										FOR XML PATH (''''))
										, 1, 2, '''') 

							ELSE
							''''
						END, '''')  [FieldValue],  Replace(field.surfaceFieldName, '' '', '''') [FieldCode]
									
						FROM pal_SurfaceField field							
									
						INNER join pal_SurfaceFieldData data on data.surfaceFieldID = field.recId 
						INNER join pal_SurfaceItem item on item.recId = data.surfaceItemId
						WHERE field.isActive = 1 AND (field.isGrid = 1 OR field.surfaceFieldName = ''ParentSurfaceItemId'') AND data.surfaceId = ' + CAST(@SurfaceID AS VARCHAR(MAX)) + ' 
						AND field.surfaceFieldTypeId IN (3,4,5,6,7,8,9,14,15,20,25,26,29,30)
						AND item.isDeleted = 0 
						) DataTable
					PIVOT
					(
						MAX(FieldValue)
						FOR FieldCode
						IN 
							(
								' + @cols + '
							)
					) PivotTable '

		--CVH 2016-10-19 If the surface has a field ParentSurfaceItemId, only select items where the value is NULL or 0
		IF (CHARINDEX('ParentSurfaceItemId', @cols) > 0) 
		BEGIN
			set @query = @query + ' WHERE ISNULL(ParentSurfaceItemId, 0) = 0 ' 
		END

print @query;
		exec sp_executesql @query;
END
