#!/bin/env python3
#
# Copyright (C) 2022 Jake Gordon, <jacob.gordon@duke.edu>
#
#    This file is part of Babase.
#
#    Babase is free software; you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Babase.  If not, see <http://www.gnu.org/licenses/>.
#
#
# When we make the babase_xxx_views schemas, we're filling them with
# views that are just copies of all the tables and views from Babase
# that are relevant to whatever "xxx" is.  Those copies-as-views
# should also have the same comment as their original does in Babase.
# However, a command like this is not allowed:
#
#   COMMENT ON VIEW someview
#     IS (SELECT foo FROM bar);
#
# In other words, we can't query a table/view's comment and use it as
# the comment for something else.  So here, we've got a bit of Python
# for make to fetch the comment from ../comments/all_comments.txt when
# creating those views.

# Takes data on stdin. Input should be a string containing the name of
# the "views" schema, then a space, then the name of the new view
# being commented on.  Next, the script reads the file at
# ../comments/all_comments.txt, and using it to make a "table/view
# name":"comment" dictionary. Using the provided new view name, the
# appropriate comment is returned.  With this comment, the script
# prints an SQL "COMMENT ON" command that will set the comment of the
# new view to that comment returned from that dictionary.
#
# Use a dictionary to do this instead of just iterating through the
# file until the right table/view name is found, to ensure that we get
# an error if the provided name returns no comment.

def writeComment(object_name, object_comment):
    '''Print an SQL "COMMENT ..." statement with these parameters'''
    print ('''COMMENT ON VIEW {0}
  IS '{1}';
'''.format(object_name, object_comment))

import sys

# Parse stdin
theInput = sys.stdin.readline().strip().split()
theSchema = theInput[0]
theView = theInput[1]
schemaDotView = theSchema + "." + theView

# Make the dict
commentsDict = {}

commentsFile = open("../comments/all_comments.txt", "r")
line = commentsFile.readline() # Skip header
line = commentsFile.readline()
while line:
    thisLine = line.strip().split("\t")
    commentsDict[thisLine[1]] = thisLine[2]
    line = commentsFile.readline()
commentsFile.close()

theComment = commentsDict[theView]

writeComment(schemaDotView, theComment)
