#!/usr/bin/env python
# coding: utf-8

import cgi
import cgitb
cgitb.enable()
from HTML_util import *
HTML_header()
import AC_util

UPDT_FS = False # Do modify filesystem accordingly
#CONFIRM = False # True if confirmation has been sent
verbose = False

form = cgi.FieldStorage()
#if verbose: print form
#HTML_headerClose(form)
#HTML_abort(form)

if 'ID' not in form:
	HTML_abort("nothing to do !")
if 'Mdb' not in form:
	HTML_abort("don't know in which collection to operate ! mention Mdb !")

ID = AC_util.isAnumber('ID', form['ID'].value)
if ID == None:
	HTML_abort(AC_util.Emsg)
Mdb = form['Mdb'].value
if Mdb not in AC_util.Mdbs:
	HTML_abort("don't know in which collection to operate ! '%s' not in Mdbs !"%Mdb)
print "<title>Delete media ID %d on collection %s</title>"%(ID,Mdb)
print '<style type="text/css">body {font-family:sans} th {text-align:right}</style>'
HTML_headerClose()

res = AC_util.getMediaRec(ID)
if res == None:
	HTML_abort("No match for ID %d"%ID)

import FS_util
CB_FS_OK = FS_util.checkMediaMounted() #False auth to bring checkbox in form to manage media file
if 'UPDT_FS' in form:
	UPDT_FS = form['UPDT_FS'].value
	if verbose:
		print 'UPDT_FS = %s<br>'%UPDT_FS
	if UPDT_FS:
		FS_util.verbose = verbose

if 'CONFIRM' in form:
	AC_util.delMediaRec(ID)
	if AC_util.con.total_changes == 1:
		cmd = "rm "
		if res['path'] != None:
			cmd += res['path']+'/'
		cmd += res['name']
		if UPDT_FS:
			#print res
			if verbose:
				print cmd+'<br>'
			ret = FS_util.updateMedia(cmd)
			if ret != 'ok':
				HTML_abort(ret)
		else:
			FS_util.log(cmd)
		AC_util.con.commit()
		print '%d deleted from %s<br>'%(ID,Mdb)
		HTML_abort("done")
	elif AC_util.con.total_changes == 0:
		print " ! Error, DB may be locked !"
	else:
		HTML_abort("Error more than one media would be deleted ! aborting")
else:
	print '<form action=""><table>'
	if 'run' in res:
		del res['run']
	#print '<pre>%s</pre>'%res
	for key in res:
		if (res[key] != None):
			print '<tr><th>%s</th><td>%s</td></tr>'%(key, AC_util.dataOut(res[key]))
	print '</table>'
	print '<input type="hidden" name="ID" value="%d">'%ID
	print '<input type="hidden" name="Mdb" value="%s">'%Mdb
	print '<input type="hidden" name="CONFIRM" value="1">'
if CB_FS_OK :
	tmp=''
	if True: #UPDT_FS
		tmp=' checked'
	print '<input type="checkbox" name="UPDT_FS" value="True"%s>\
	 Do modify filesystem accordingly<br>'%tmp
	print '<input type="submit" value="Confirm DELETE" /></form>'
HTML_abort()
