#!/usr/bin/env python

import argparse
import yaml
import jagss
import os
import SimpleHTTPServer
import SocketServer
import subprocess
import threading
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from jagss.sftpsync import Sftp
from jagss.createSite import createNewSite


class jagssServerThread(threading.Thread):
    def __init__(self, port, outputDir):
        threading.Thread.__init__(self)
        self.PORT = port
        self.outputDir = outputDir
        self.Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
        self.httpd = SocketServer.TCPServer(("", self.PORT), self.Handler)

    def run(self):
        os.chdir(self.outputDir)
        print 'serving at http://localhost:' + str(self.PORT)
        self.httpd.serve_forever()

    def shutdown(self):
        self.httpd.shutdown()


class jagss_handler(FileSystemEventHandler):
    def __init__(self, configDict):
        FileSystemEventHandler.__init__(self)
        self.configDict = configDict

    def on_any_event(self, event):
        if not event.src_path.startswith(self.configDict['outputDir']):
            print 'rebuilding static site...'
            jagss.buildStaticSite(self.configDict['sourceDir'],
                                  self.configDict['outputDir'],
                                  self.configDict['templatesDir'],
                                  self.configDict['lessFile'],
                                  self.configDict['sassFile'])
            print 'rebuild complete.\n'


def main():
    parser = argparse.ArgumentParser()
    createhelp = "Create new project in current directory. "
    createhelp += "Options are: 'css' and 'less'. ('sass' coming soon)"
    parser.add_argument("--create", metavar='CSS_PROCESSOR', help=createhelp)
    confighelp = "Specify config file. If this option is not specified, "
    confighelp += "jagss will look in the current directory for one."
    parser.add_argument("--config", metavar='/path/to/config.yaml',
                        help=confighelp)
    parser.add_argument("--server", metavar='PORT',
                        help="run a server for testing on Port #")
    deployhelp = "Sync generated html with external server. "
    deployhelp += "Options are 'sftp' and 's3'."
    parser.add_argument("--deploy", metavar='TYPE',
                        help=deployhelp)
    args = parser.parse_args()
    if args.create:
        createNewSite(os.getcwd(), args.create)
    if args.config:
        configDict = yaml.load(file(args.config, 'r'))
    elif 'config.yaml' in os.listdir(os.getcwd()):
        configFile = file(os.path.join(os.getcwd(), 'config.yaml'), 'r')
        configDict = yaml.load(configFile)
    else:
        configDict = False
    if configDict:
        jagss.buildStaticSite(configDict['sourceDir'],
                              configDict['outputDir'],
                              configDict['templatesDir'],
                              configDict['lessFile'],
                              configDict['sassFile'])
    else:
        print 'ERROR: Could not find config.yaml file.'
        return False
    if args.deploy:
        if args.deploy == 'sftp':
            print 'deploying to sftp site: ' + configDict['sftpAddress']
            sftpsite = Sftp(configDict['sftpAddress'],
                            configDict['sftpUsername'],
                            configDict['sftpPassword'])
            sftpsite.sync(configDict['outputDir'], configDict['sftpDirectory'],
                          download=False, delete=True)
        if args.deploy == 's3':
            print 'deplying to s3 bucket: ' + configDict['s3BucketName']
            commandList = ['boto-rsync', '-a', configDict['s3AccessKey'],
                           '-s', configDict['s3SecretKey'], '--delete',
                           configDict['outputDir'] + '/',
                           's3://' + configDict['s3BucketName'] + '/']
            subprocess.call(commandList)
        if args.deploy == 'git':
            print 'deploying via git not implemented yet'
    if args.server:
        event_handler = jagss_handler(configDict)
        observer = Observer()
        masterDir = os.path.dirname(configDict['sourceDir'])
        observer.schedule(event_handler, path=masterDir, recursive=True)
        portNum = int(args.server)
        jagssHttpServer = jagssServerThread(portNum, configDict['outputDir'])
        observer.start()
        jagssHttpServer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
            jagssHttpServer.shutdown()
            print 'stopping testing server.\n'
        observer.join()

if __name__ == "__main__":
    main()
