#!/usr/bin/env python

'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.'''

import json
import md5
from os import makedirs,walk,path,stat
from pprint import pprint
from MediaInfoDLL import MediaInfo,Stream
from time import gmtime,strftime,strptime
from collections import OrderedDict

basedir = '/data2/tvheadend'
confdir = basedir + '/conf'
chanconfdir = confdir + '/epggrab/xmltv/channels'
dvrconfdir = confdir + '/dvr/log'
recdir = basedir + '/recordings'
recdir = '/data2/media/TV/recordings'
tempdir = '/tmp/dvr'

channelDefault = '6a175a7e089130b4b7909ef42a040e84'
channelNameDefault = 'Cartoonito'

channelfiles = []
for (dirpath, dirnames, filenames) in walk(chanconfdir):
 channelfiles.extend(filenames)
 break

d_channeldata = dict()

for channelfile in channelfiles:
 with open('%s/%s' % (chanconfdir,channelfile)) as j_channel:    
  channeldata = json.load(j_channel)
  d_channeldata[channeldata['name']] = channeldata

movies = list()
for (dirpath, dirnames, filenames) in walk(recdir):
 for filename in filenames:
  if filename.split('.')[-1] == 'mkv':
   movies.append( path.join(dirpath,filename) )

for movieFile in movies:
 movie = MediaInfo()
 movie.Open(movieFile)
 duration = movie.Get(Stream.Video,0,"Duration")
 startDate = movie.Get(Stream.General,0,"DATE_BROADCASTED")
 if startDate == '':
  startDate = strftime('%Y-%m-%d %H:%M:%S',gmtime(float(stat(movieFile)[9])))
 channel = movie.Get(Stream.General,0,"TVCHANNEL")
 if channel == '':
  channel = channelNameDefault
 summary = movie.Get(Stream.General,0,"SUMMARY")
 title = movie.Get(Stream.General,0,"Title")
 if title == '':
  title = path.splitext(path.basename(movieFile))[0]
 movie.Close()
 
 movieDict = OrderedDict()
 startTime = strftime('%s',strptime(startDate,'%Y-%m-%d %H:%M:%S'))
 stopTime = str( int('0'+startTime) + ( int('0'+duration) / 1000 ) )
 movieDict['start'] = startTime
 movieDict['start_extra'] = '0'
 movieDict['stop'] = stopTime
 movieDict['stop_extra'] = '0'
 try:
  movieDict['channel'] = d_channeldata[channel]['channels'][0]
 except KeyError:
  movieDict['channel'] = ''
 movieDict['channelname'] = channel
 movieDict['title'] = { 'ita': title }
 movieDict['description'] = { 'ita': summary }
 movieDict['pri'] =  2
 movieDict['retention'] =  0
 movieDict['container'] =  -1
 movieDict['config_name'] =  "fb4a4ca99788b954709fc0a407206be5"
 movieDict['creator'] =  "rebuild"
 movieDict['filename'] =  movieFile
 movieDict['errorcode'] =  0
 movieDict['errors'] =  0
 movieDict['dvb_eid'] =  0
 movieDict['noresched'] =  False
 movieDict['autorec'] =  ""
 movieDict['timerec'] =  ""
 movieDict['content_type'] =  0
 movieDict['broadcast'] =  00000000

 #outFileName = dvrconfdir + '/' + md5.md5(movieDict).hexdigest()
 if not path.exists(tempdir):
  makedirs(tempdir)
 outFileName = '/tmp/dvr/' + md5.md5(str(movieDict)).hexdigest()
 with open(outFileName,'wb') as a:
  json.dump(movieDict,a,indent=8)
  a.write('\n')
