import re
import os
import shutil
import settings

mock_dir = "mocking"

def gen_mocks(err_lnks, sources, owners, defurl):
  mock_locs = {}
  if not os.path.isdir(mock_dir) or not os.path.exists(mock_dir):
    os.mkdir(mock_dir)
  else:
    shutil.rmtree(mock_dir)
    os.mkdir(mock_dir)
  for person in set(owners.values()):
    os.mkdir('%s/%s' % (mock_dir, person.split("@")[0]))
    
  for (url, errlnk) in err_lnks.iteritems():

    bklnks = errlnk[0].keys()
    bklnks.extend(errlnk[1].keys())
    if len(bklnks) == 0:
      continue      
    source = sources[url]
    to_insert = update_css(source, url)
    for bkurl in bklnks:
      rpos = errlnk[2][bkurl]
      pos = source.find(">", rpos)
      if "style" in source[rpos:pos]:
        if "background-color" in source[rpos:pos]:
          pos = source.find("background-color", rpos)
          pos += len("background-color:")
          to_insert[pos] = "yellow"
        else:
          pos = source.find("style", rpos)
          pos += len('style="')
          to_insert[pos] = "background-color:yellow "
      else:
        to_insert[pos] = ' style="background-color:yellow"'
    source = insert_in_source(to_insert, source)
    sources[url] = source
    
    if "~" in url:
      tpos = url.find("~")+1
      epos = url.find("/", tpos)
      if epos == -1:
        own = url[tpos:]
      else:
        own = url[tpos:epos]
      ourl = "http://www.doc.ic.ac.uk/~" + own
    else:
      maxlen = 0
      for ownurl in owners:
        if ownurl in url and len(ownurl) > maxlen:
          own = owners[ownurl]
          maxlen = len(ownurl)
          ourl = ownurl
      if maxlen == 0:
        own = owners['default']
      ourl = defurl
    
    own = own.split("@")[0]
    if url.endswith("/"):
      url = url[:-1]
    if ourl.endswith("/"):
      ourl = ourl[:-1]
    spos = url.find(ourl) + len(ourl)
    path = "%s/%s" % (mock_dir, own)
    if not os.path.exists(path) or not os.path.isdir(path):
      os.mkdir(path)
    if spos < len(url):
      if url[spos] != '/':
        print "Error matching URLs, trying to rectify: %s - %s" % (url, ownurl)
        spos = url.find("/", spos)
      npos = url.find("/", spos+1)
      while npos != -1:
        newdir = url[spos+1:npos]
        path += "/%s" % (newdir)
        if not os.path.exists(path):
          os.mkdir(path)
        spos = npos
        npos = url.find("/", spos+1)
        
    f = open('%s/%s.html' % (path, url[url.rfind("/")+1:]), 'w')
    f.write(source)
    f.close()
    mock_locs[url] = path
  return mock_locs
 
def insert_in_source (to_insert, source):
  offset = 0
  for pos in sorted(to_insert):
    source = source[:pos+offset] + to_insert[pos] + source[pos+offset:]
    offset += len(to_insert[pos])
  return source
  
def update_css (source, url):
  parent = url[:[m.start() for m in re.finditer("/", url)][2]]
  to_insert = {}
  offset = 0
  for match in re.finditer('type="text/css"', source):
    pos = source.find("href", match.start()) + len('href="')
    epos = source.find('"', pos)
    cssurl = source[pos:epos]
    if cssurl.startswith("/"):
      to_insert[pos] = parent
    elif not cssurl.startswith("http"):
      to_insert[pos] = url[:url.rfind('/')+1]
  return to_insert
    
