#!/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 BaseHTTPServer
import CGIHTTPServer
import cgitb
cgitb.enable()  # This line enables CGI error reporting
import socket
import thread
import webbrowser
import os


class StoppableHTTPServer(BaseHTTPServer.HTTPServer):

    def server_bind(self):
        BaseHTTPServer.HTTPServer.server_bind(self)
        self.socket.settimeout(1)
        self.run = True

    def get_request(self):
        while self.run:
            try:
                sock, addr = self.socket.accept()
                sock.settimeout(None)
                return (sock, addr)
            except socket.timeout:
                pass

    def stop(self):
        self.run = False

    def serve(self):
        while self.run:
            self.handle_request()


if __name__ == "__main__":
    os.chdir(os.path.dirname(os.path.realpath(__file__)))
    httpd = StoppableHTTPServer(("", 8000),
    CGIHTTPServer.CGIHTTPRequestHandler)
    thread.start_new_thread(httpd.serve, ())
    webbrowser.open("http://localhost:8000/cgi-bin/editor.py")
    raw_input("Press <RETURN> to stop server\n")

    httpd.stop()
