#!/usr/bin/env python
##################################################################
# Upgrade pmm/table-config.xml from 3.0 to 3.1.010
##################################################################
import os
import xml.etree.ElementTree as ET

tableConfigPath = "/opt/tandbergtv/cms/conf/pmm/table-config.xml"

def buildElementTree(tables):
	table = ET.SubElement(tables, 'table')
	table.set('defaultColumnWidth', '')
	table.set('actionPath', '')
	table.set('defaultSortingOrder', 'DESCENDING')
	table.set('defaultSortingColumn', 'id')
	table.set('id', 'sitesActivityColumns')

	column1 = ET.SubElement(table, "Column")
	columnName1 = ET.SubElement(column1, "ColumnName")
	columnName1.text = "Title ID"
	methodName1 = ET.SubElement(column1, "MethodName")
	methodName1.text = "id"
	sortingColumnName1 = ET.SubElement(column1, "SortingColumnName")
	sortingColumnName1.text = "id"

	column2 = ET.SubElement(table, "Column")
	columnName2 = ET.SubElement(column2, "ColumnName")
	columnName2.text = "Status"
	methodName2 = ET.SubElement(column2, "MethodName")
	methodName2.text = "status"
	sortingColumnName2 = ET.SubElement(column2, "SortingColumnName")
	sortingColumnName2.text = "status"

	column3 = ET.SubElement(table, "Column")
	columnName3 = ET.SubElement(column3, "ColumnName")
	columnName3.text = "Thumbnail"
	methodName3 = ET.SubElement(column3, "MethodName")
	methodName3.text = "thumbnail"

	column4 = ET.SubElement(table, "Column")
	columnName4 = ET.SubElement(column4, "ColumnName")
	columnName4.text = "Status Update Time"
	methodName4 = ET.SubElement(column4, "MethodName")
	methodName4.text = "statusUpdateTime"
	sortingColumnName4 = ET.SubElement(column4, "SortingColumnName")
	sortingColumnName4.text = "statusUpdateTime"

	column5 = ET.SubElement(table, "Column")
	TableExtensionKey = ET.SubElement(column5, "TableExtensionKey")
	TableExtensionKey.text = "targetedTitlesAssetMetadata"
	TableExtensionLoaderImpl = ET.SubElement(column5, "TableExtensionLoaderImpl")
	TableExtensionLoaderImpl.text = "com.tandbergtv.watchpoint.pmm.web.title.TitleTableExtensionLoader"

	return tables

if os.path.exists(tableConfigPath):
	tree = ET.parse(tableConfigPath)
	tables = tree.getroot()

	isSitesActivityColumnsExist = False

	for table in tables.findall('table'):
		if table.attrib["id"] == 'sitesActivityColumns':
			isSitesActivityColumnsExist = True
			print "sitesActivityColumns already exist"

	if isSitesActivityColumnsExist == False:
		buildElementTree(tables)
		tree.write(open(tableConfigPath, 'w'), encoding='UTF-8')

else:
	print "pmm/table-config.xml Does not exist."
