#
#   GitHub Issue Reporter Module for XBMC Addons
#
#   Copyright (c) 2014 Adam Malcontenti-Wilson
#
#   Permission is hereby granted, free of charge, to any person obtaining a copy
#   of this software and associated documentation files (the "Software"), to deal
#   in the Software without restriction, including without limitation the rights
#   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#   copies of the Software, and to permit persons to whom the Software is
#   furnished to do so, subject to the following conditions:
#
#   The above copyright notice and this permission notice shall be included in
#   all copies or substantial portions of the Software.
#
#   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#   THE SOFTWARE.
#

import base64
import os
import re
import sys
import urllib2
import xbmc
import issue_reporter_utils as utils

from datetime import datetime
from os.path import join, normpath, dirname, abspath, isfile

try:
  import simplejson as json
except ImportError:
  import json

LOG_FILTERS = (
  ('//.+?:.+?@', '//[FILTERED_USER]:[FILTERED_PASSWORD]@'),
  ('<user>.+?</user>', '<user>[FILTERED_USER]</user>'),
  ('<pass>.+?</pass>', '<pass>[FILTERED_PASSWORD]</pass>'),
)

VERSION = utils.get_module_version()

class IssueReporter:
  def __init__(self, config={}):
    self.config = utils.build_config(config)

    if 'logger' in self.config:
      self.log = self.config['logger']
    else:
      # Fallback logger, it is recommended to pass one in as the default
      # is pretty ugly in the XBMC logs
      self.log = utils.build_logger(__name__)

  def make_request(self, url):
    """
        Make our JSON request to GitHub
    """
    return urllib2.Request(url, headers={
      "Authorization": "Basic %s" % self.config['github_api_auth'],
      "Content-Type": "application/json",
      "User-Agent": '%s/%s script.module.githubissuereporter/%s' % (self.config['addon_id'], self.config['addon_version'], VERSION)
    })

  def get_public_ip(self):
    """
        Try and fetch the public IP of the reporter for logging
        and reporting purposes
    """
    try:
        result = urllib2.urlopen('http://ipecho.net/plain', timeout=5)
        data = str(result.read())
    except:
        return "Unknown (lookup failure)"

    try:
        ip = re.compile(r'(\d+\.\d+\.\d+\.\d+)').search(data).group(1)
    except:
        return "Unknown (parse failure)"

    try:
        hostname = socket.gethostbyaddr(ip)[0]
        return "%s (%s)" % (ip, hostname)
    except:
        return ip


  def get_isp(self):
    """
        Try and fetch the ISP of the reporter for logging
        and reporting purposes
    """
    try:
        result = urllib2.urlopen('http://www.whoismyisp.org', timeout=5)
        data = str(result.read())
    except:
        return "Unknown (lookup failure)"

    try:
        isp = re.compile(r'<h1>(.*)</h1>').search(data).group(1)
    except:
        return "Unknown (parse failure)"

    return isp

  def get_system_time(self):
    """
        Fetch the current system time
    """
    now = datetime.utcnow()
    return "%04d-%02d-%02d %02d:%02d:%02d (UTC)" % (now.year, now.month, now.day, now.hour, now.minute, now.second)

  def get_xbmc_log(self):
    """
        Fetch and read the XBMC log
    """
    log_path = xbmc.translatePath('special://logpath')
    log_file_path = os.path.join(log_path, 'xbmc.log')
    self.log.debug("Reading log file from \"%s\"" % log_file_path)
    with open(log_file_path, 'r') as f: