#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Query tools
#
# Software is free software released under the "Modified BSD license"
#
# Copyright (c) 2014-2015   Alexandre Dulaunoy - a@foo.be
# Copyright (c) 2014-2015 	Pieter-Jan Moreels - pieterjan.moreels@gmail.com

import urllib.parse
import requests

import os
import sys
runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))

import lib.CVEs          as cves
import lib.DatabaseLayer as db
import lib.Toolkit       as tk

from lib.Config import Configuration

rankinglookup = True
redisdb = Configuration.getRedisVendorConnection()

def findranking(cpe=None, loosy=True):
  if cpe is None:
    return False
  result = False
  if loosy:
    for x in cpe.split(':'):
      if x is not '':
        i = db.findRanking(cpe, regex=True)
      if i is None:
        continue
      if 'rank' in i:
        result = i['rank']
  else:
    i = db.findRanking(cpe, regex=True)
    print (cpe)
    if i is None:
      return result
    if 'rank' in i:
      result = i['rank']
  return result

def lookupcpe(cpeid=None):
    e = db.getCPE(cpeid)
    if e is None:
        return cpeid
    if 'id' in e:
        return e['title']


def lastentries(limit=5, namelookup=False, rankinglookup=True):
  entries = []
  for item in db.getCVEs(limit):
    if not namelookup and rankinglookup is not True:
      entries.append(item)
    else:
      if "vulnerable_configuration" in item:
        vulconf = []
        ranking = []
        for conf in item['vulnerable_configuration']:
          if namelookup:
            vulconf.append(lookupcpe(cpeid=conf))
          else:
            vulconf.append(conf)
          if rankinglookup:
            rank = findranking(cpe=conf)
            if rank and rank not in ranking:
              ranking.append(rank)
        item['vulnerable_configuration'] = vulconf
        if rankinglookup and len(ranking) > 0:
          item['ranking'] = ranking
      entries.append(item)
  return entries

def apigetcve(api, cveid=None):
  if cveid is None:
    return False
  url = urllib.parse.urljoin(api, "api/cve/"+cveid)
  urltoget = urllib.parse.urljoin(url, cveid)
  r = requests.get(urltoget)
  if r.status_code is 200:
    return r.text
  else:
    return False

def apibrowse(api, vendor=None):
  url = urllib.parse.urljoin(api, "api/browse")
  if vendor is None:
    r = requests.get(url)
  else:
    urlvendor = url + "/" + vendor
    r = requests.get(urlvendor)

  if r.status_code is 200:
    return r.text
  else:
    return False

def apisearch(api, query=None):
  if query is None:
    return False
  url = urllib.parse.urljoin(api, "api/search/")
  url = url+query

  r = requests.get(url)
  if r.status_code is 200:
    return r.text
  else:
    return False



# Lastly added
def cvesForCPE(cpe):
  cpe  = tk.toStringFormattedCPE(cpe)
  data = []
  if cpe:
    cvesp = cves.last(rankinglookup=False, namelookup=False, via4lookup=True, capeclookup=False)
    for x in db.cvesForCPE(cpe):
        data.append(cvesp.getcve(x['id']))
  return data

def getBrowseList(vendor):
  result = {}
  if (vendor is None) or type(vendor) == list:
    v1 = redisdb.smembers("t:/o")
    v2 = redisdb.smembers("t:/a")
    v3 = redisdb.smembers("t:/h")
    vendor = sorted(list(set(list(v1) + list(v2) + list(v3))))
    cpe = None
  else:
    cpenum = redisdb.scard("v:" + vendor)
    if cpenum < 1:
      return None
    p = redisdb.smembers("v:" + vendor)
    cpe = sorted(list(p))
  result["vendor"] = vendor
  result["product"] = cpe
  return result

def getVersionsOfProduct(product):
  p = redisdb.smembers("p:" + product)
  return sorted(list(p))
