import re, os, os.path, datetime
import Media, VideoFiles, Stack, Utils

def Scan(path, files, mediaList, subdirs):
  files.sort()
  if len(files) >= 1:

    # Iterate through all the files
    for i,file in enumerate(files):

      # Remove path and extension
      tsfile = os.path.basename(file)
      tsfile = os.path.splitext(tsfile)[0]

      # Enigma2 files look like: YYYYMMDD HHMM - Channel - Programmename.ts
      #(date_time,channel,programme) = tsfile.split(' - ',2)
      #(date,time) = date_time.split(' ')

      #year = int(date[0:4])
      #month = int(date[4:6])
      #day = int(date[6:8])
      #hour = int(time[0:2])
      #minute = int(time[2:4])
      #d = datetime.datetime(year, month, day, hour, minute)
      #t = d.timetuple()

      show = os.path.basename(os.path.dirname(file))

      tsfile = tsfile.replace(show, "")

      #title = channel+" - "+date[6:8]+"/"+date[4:6]+"/"+date[0:4]+" "+time[0:2]+":"+time[2:4]
      title = tsfile

      paths = Utils.SplitPath(path)
      season = None
      if len(paths) == 2:
        show = paths[0]
        match = re.search('(?P<season>[0-9]+)', paths[1])
        if match:
          season = match.group('season')
        else:
          title = paths[1] + '/' + title

      tv_show = Media.Episode(show,season,None,title,None)
      tv_show.released_at = datetime.datetime.fromtimestamp(os.stat(file).st_mtime).strftime("%Y-%m-%d")
      tv_show.parts.append(file)
      mediaList.append(tv_show)