#!/usr/bin/env python
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# Copyright 2013 Mike Hingley
#
# This file is part of Synfig Scene Builder
#
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3, as published
#by the Free Software Foundation.

#This program is distributed in the hope that it will be useful, but
#WITHOUT ANY WARRANTY; without even the implied warranties of
#MERCHANTABILITY, SATISFACTORY QUALITY, 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 this program.  If not, see <http://www.gnu.org/licenses/>.
import os
import cgi
from configuration import Configuration
#from os import remove, close, listdir
#from os.path import isfile, join
import jinja2
import sys
import re
#from cgi import escape
from os.path import expanduser

#=============================================================================
#SERVER_NAME = str(os.environ['SERVER_NAME'])
#SERVER_PORT = str(os.environ['SERVER_PORT'])
#SCRIPT_NAME = str(os.environ['SCRIPT_NAME'])
PROJECT_LOCATION = os.getcwd()


import os


def SacnFolder(walk_dir,filter):
	castFiles = []
	for path, subdirs, files in os.walk(walk_dir):
	    for name in files:
	        if name.endswith('.sif'):
	            print os.path.join(path, name)
				tmp = str(path) + '/' + name
				tmp=tmp.replace(walk_dir,"");
 				castFiles.append(tmp)

	return castFiles



TEMP_FOLDER = os.path.join(os.getcwd(), 'temp')
for the_file in os.listdir(TEMP_FOLDER):
    file_path = os.path.join(TEMP_FOLDER, the_file)
    try:
        if os.path.isfile(file_path):
            os.unlink(file_path)
    except Exception, e:
        print e

templateLoader = jinja2.FileSystemLoader(searchpath=PROJECT_LOCATION)
templateEnv = jinja2.Environment(loader=templateLoader)
TEMPLATE_FILE = "synfig-scene-builder.html"
template = templateEnv.get_template( TEMPLATE_FILE)


#get file list from CAST folder.

from os import listdir
from os.path import isfile, join

path = os.path.join(PROJECT_LOCATION,'synfig-scene-builder.config')
c = Configuration(path)
castfolder = expanduser(c.Cast_Location())
isRecursive = c.Scan_Recursive()


if not os.path.exists(castfolder):
    os.makedirs(castfolder)

if isRecursive :
	cast = SacnFolder(castfolder,'.sif')
else:
	cast = [f for f in listdir(castfolder) if f.endswith('.sif')]



configuration = c.GetDictionary()


templateVars = {
"cast": cast,
"configuration":configuration
 }
outputText = template.render(templateVars)

print outputText
