create or replace PROCEDURE  "AP-RARTABLEAU".RECREATE_TABLE (
    viewName IN VARCHAR2
) AS
    v_exists NUMBER;
    sqlText CLOB;
    v_err_msg VARCHAR2(4000 CHAR) := 'Job succeded';
BEGIN

    UPDATE "AP-RARTABLEAU".TABLEAU_DASHBOARDS_DEFINITIONS 
    SET LAST_REFRESH_START = SYSDATE,
        LAST_REFRESH_END = NULL,
        LAST_REFRESH_STATUS = 'RUNNING',
		ERROR_MESSAGE = NULL		
    WHERE DASHBOARD_NAME = viewName;
    commit;

    SELECT COUNT(*)
    INTO v_exists
    FROM USER_TABLES
    WHERE TABLE_NAME = UPPER(viewName);

    SELECT SQL_TEXT
    INTO sqlText
    FROM "AP-RARTABLEAU".TABLEAU_DASHBOARDS_DEFINITIONS 
    WHERE DASHBOARD_NAME = viewName;

    -- Drop the materialized view if it exists
    IF v_exists > 0 THEN
        EXECUTE IMMEDIATE 'DROP TABLE "AP-RARTABLEAU".' || viewName;
    END IF;

    -- Create the materialized view
    EXECUTE IMMEDIATE 'CREATE TABLE  "AP-RARTABLEAU".' || viewName || ' AS ' || sqlText;
    EXECUTE IMMEDIATE 'GRANT SELECT ON  "AP-RARTABLEAU".' || viewName || ' TO "AP-RARTABLEAU"';
    EXECUTE IMMEDIATE 'GRANT SELECT ON  "AP-RARTABLEAU".' || viewName || ' TO "RAR_RO"';

    -- close info in PDBADMIN.TABLEAU_DASHBOARDS_DEFINITIONS 
    UPDATE "AP-RARTABLEAU".TABLEAU_DASHBOARDS_DEFINITIONS 
    SET LAST_REFRESH_END = SYSDATE,
        LAST_REFRESH_STATUS = 'SUCCESS'
    WHERE DASHBOARD_NAME = viewName;
    commit;
EXCEPTION
    WHEN OTHERS THEN
		v_err_msg := SQLCODE ||': '|| SQLERRM; 
        UPDATE "AP-RARTABLEAU".TABLEAU_DASHBOARDS_DEFINITIONS 
        SET LAST_REFRESH_END = SYSDATE,
            LAST_REFRESH_STATUS = 'FAILED',
			ERROR_MESSAGE = v_err_msg
        WHERE DASHBOARD_NAME = viewName;
        commit;
END;
/
