# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import base64
import hashlib
import heapq
import json
import logging
import os
import re
import select
import socket
import subprocess
import sys
import time
import urlparse

import BaseHTTPServer

_unittests_running = False

class ChromeNotFoundException(Exception):
  pass

class _PossibleDesktopBrowser(object):
  def __init__(self, browser_type, executable):
    self.browser_type = browser_type
    self.local_executable = executable

  def __repr__(self):
    return '_PossibleDesktopBrowser(browser_type=%s)' % self.browser_type

def _samefile(a, b):
  if sys.platform != 'win32':
    return os.path.samefile(a, b)
  return os.path.abspath(a) == os.path.abspath(b)

def _FindAllAvailableBrowsers():
  """Finds all the desktop browsers available on this machine."""
  browsers = []

  has_display = True
  if (sys.platform.startswith('linux') and
      os.getenv('DISPLAY') == None):
    has_display = False

  def AddIfFound(browser_type, browser_dir, app_name):
    app = os.path.join(browser_dir, app_name)
    if os.path.exists(app):
      browsers.append(_PossibleDesktopBrowser(browser_type,
                                              app))
      return True
    return False

  # Look for a browser in the standard chrome build locations.
  if sys.platform == 'darwin':
    chromium_app_name = 'Chromium.app/Contents/MacOS/Chromium'
  elif sys.platform.startswith('linux'):
    chromium_app_name = 'chrome'
  elif sys.platform.startswith('win'):
    chromium_app_name = 'chrome.exe'
  else:
    raise Exception('Platform not recognized')

  # Mac-specific options.
  if sys.platform == 'darwin':
    mac_canary = ('/Applications/Google Chrome Canary.app/'
                 'Contents/MacOS/Google Chrome Canary')
    mac_system = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
    if os.path.exists(mac_canary):
      browsers.append(_PossibleDesktopBrowser('canary',
                                             mac_canary))

    if os.path.exists(mac_system):
      browsers.append(_PossibleDesktopBrowser('system',
                                             mac_system))

  # Linux specific options.
  if sys.platform.startswith('linux'):
    # Look for a google-chrome instance.
    found = False
    try:
      with open(os.devnull, 'w') as devnull:
        found = subprocess.call(['google-chrome', '--version'],
                                stdout=devnull, stderr=devnull) == 0
    except OSError:
      pass
    if found:
      browsers.append(
          _PossibleDesktopBrowser('system',
                                 'google-chrome'))

  # Win32-specific options.
  if sys.platform.startswith('win'):
    system_path = os.path.join('Google', 'Chrome', 'Application')
    canary_path = os.path.join('Google', 'Chrome SxS', 'Application')

    win_search_paths = [os.getenv('PROGRAMFILES(X86)'),
                        os.getenv('PROGRAMFILES'),
                        os.getenv('LOCALAPPDATA')]

    for path in win_search_paths:
      if not path:
        continue
      if AddIfFound('canary', os.path.join(path, canary_path),
                    chromium_app_name):
        break

    for path in win_search_paths:
      if not path:
        continue
      if AddIfFound('system', os.path.join(path, system_path),
                    chromium_app_name):
        break

  if len(browsers) and not has_display:
    logging.warning(
      'Found (%s), but you do not have a DISPLAY environment set.' %
      ','.join([b.browser_type for b in browsers]))
    return []

  return browsers



_ExceptionNames = {
  404: 'Not found',