#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
''' Simply open browser 1 seconds after start server,
    As we don't want to use hooking
    which need rewrite HttpServer.run() '''
import os
import sys
import time

from multiprocessing import Process

from instant_rst import args
from instant_rst.http import post
from instant_rst.server import run, shutdown_server

import socket

def which(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

def browse(b, port, filename):
    time.sleep(1)
    url =  'http://' + HOST + ':'+ port

    if sys.platform.startswith('darwin'):
        if b:
            os.system('open -a "'+b+'" ' + url+ ' &')
        else:
            os.system('open '+ url+ ' &')
    elif os.name == 'nt':
        if b:
            os.system('start "'+ b+'" ' + url)
        else:
            os.system('start ' + url)
    elif os.name == 'posix':
        linux = ['xdg-open','kioclient', 'exo-open', 'gnome-open', 'cygstart']
        for o in linux:
            if which(o):
                if b:
                    # xdg-open or gnome-open will use the default app only.
                    os.system('"' + b + '" ' + url + ' &')
                else:
                    os.system(o + ' ' + url + ' &')
                break
    time.sleep(1)
    post(url, {'file': filename})

ag = args.parse()

if ag.localhost_only:
    HOST = "localhost"
else:
    # get hostname of local LAN IP
    HOST = socket.gethostbyname(socket.gethostname())


if not ag.debug:
    p = Process(target=browse, args=(ag.browser, ag.port, ag.filename))
    p.start()

try:
    run(host=HOST, port=int(ag.port),
        template_dir=ag.template_dir,
        static_dir=ag.static_dir,
        additional_dirs=ag.additional_dirs,
        default_file=ag.filename
        )
except:
    print '\nSome error/exception occurred.'
    print sys.exc_info()
    if not ag.debug:
        p.terminate()
    sys.exit()
