-------------
-- ROLES
-------------
	USE [IHBoxSystem]
	GO
	CREATE ROLE ctemp_read AUTHORIZATION dbo 
	GO  

	USE [IHBoxSystem]
	GO
	EXEC sp_addrolemember 'ctemp_read', 'admin'
	GO

	USE [IHBoxSystem]
	GO
	EXEC sp_addrolemember 'ctemp_read', 'SDI/australtek'
	GO



-------------------
-- Menu and Route
-------------------
	declare @parent int, @result_routeId INT
	select @parent=id from [FrontEnd].[Menu] where [Name] = 'Caster' and Parent is null

	INSERT INTO [FrontEnd].[Routes]
			   ([Route]
			   ,[ModuleName]
			   ,[ModulePath]
			   ,[RequiredRole]
		   )
		 VALUES 
			   (
			   '!/covers-temperatures'
			   , 'covers-temperatures'
			   , 'pages/caster/covers-temperatures/'
			   , 'ctemp_read'           
			   )
			   SET @result_routeId = @@IDENTITY
	INSERT INTO [FrontEnd].[Menu]
			   ([Parent]
			   ,[Name]
			   ,[RouteID]
			   ,[SortOrder]
			   ,[Enabled]
			   ,[Visible]
			   ,[RequiredRole]
			   ,[Group]
			  )
		 VALUES
			   (
			   @parent
			   ,'Covers Temperatures'
			   ,@result_routeId 
			   ,1
			   ,1
			   ,1
			   ,'ctemp_read'
			   ,NULL
			 )
	GO


-------------------
-- SP Permissions
-------------------
EXECUTE sys.sp_addextendedproperty 
@level0type = N'USER' -- The object type
,@level0name = [ctemp_read] -- The role
,@name = N'securedsp-CAS.GetLastCoverTemperatures' -- the procedure
,@value = N'' 
GO


-------------------
--	Profiles
-------------------
	USE [IHBoxSystem]
	GO

	DECLARE @ModuleId INT

	INSERT INTO [SECURITY].[Modules]([Code],[Name])
	VALUES('ctemp_read','Covers Temperatures')

	SET @ModuleId = @@IDENTITY


	INSERT INTO [SECURITY].ModuleActions(ModuleId,Code,[Name],[Role])
	VALUES (@ModuleId,'read','Read','ctemp_read')




USE [MES]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [CAS].[GetLastCoverTemperatures]
AS
BEGIN
	
	SELECT DISTINCT CoverNumber from CAS.CoverTemps;


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


SELECT @cols = STRING_AGG(CONCAT('MAX(CASE WHEN CoverNumber = ', CoverNumber, 
                                 ' THEN TempSensor1 END) AS [C', CoverNumber, 'S1], ',
                                 'MAX(CASE WHEN CoverNumber = ', CoverNumber, 
                                 ' THEN TempSensor2 END) AS [C', CoverNumber, 'S2]'), ', ')
FROM (
    SELECT DISTINCT CoverNumber 
    FROM [CAS].[CoverTemps]
) AS CoverNumbers;

-- GET Last 30 minutes
SET @query = '
SELECT top 30 FORMAT([Timestamp], ''yyyy-MM-dd HH:mm'') AS [Timestamp], ' + @cols + '
FROM [MES].[CAS].[CoverTemps]
GROUP BY FORMAT([Timestamp], ''yyyy-MM-dd HH:mm'')
ORDER BY FORMAT([Timestamp], ''yyyy-MM-dd HH:mm'') desc;'

EXEC sp_executesql @query;


END
