# -*- Mode: Python; -*-
# -*- coding: utf-8 -*-
# vi:si:et:sw=2:sts=2:ts=2

from datetime import datetime
import time

import md5
import simplejson
from scrapeit.utils import stripTags

import model
import utils

def jsonLoadArchiveItem(data):
  json_array = simplejson.loads(data)
  json_array.pop('tg_flash', None)
  if json_array.has_key('archiveURL'):
    json_array['archiveUrl'] = json_array.pop('archiveURL')
  if json_array.has_key('downloadURL'):
    json_array['downloadUrl'] = json_array.pop('downloadURL')
  if json_array.has_key('storeURL'):
    json_array['storeUrl'] = json_array.pop('storeURL')
  for key in ('relDate', 'pubDate', 'modDate'):
    json_array[key] = datetime.utcfromtimestamp(float(json_array[key]))
  for key in ('rightsLevel', 'size'):
    json_array[key] = int(json_array[key])

  json_array['fileType'] = json_array.pop('type', 'unknown')
  for key in ('title', 'description'):
    json_array[key] = stripTags(json_array[key])
  for key in ('storeUrl', 'archiveUrl', 'title', 'description'):
    json_array[key] = json_array.get(key, u'')
  json_array['html'] = utils.fix_ampersands(json_array['html'])
  return json_array


def jsonImportArchiveItem(archive, archiveItemId, json_array):
  if isinstance(json_array, basestring):
    json_array = jsonLoadArchiveItem(json_array)
  salt = u'%s/%s' % (archive.archiveName, archiveItemId)
  hashID = md5.new(salt.encode('utf-8')).hexdigest()
  i = model.ArchiveItem(
    archiveID=archive.id,
    hashId = hashID,
    archiveItemId = "%s" % archiveItemId,
    description=json_array['description'],
    rightsLevel=json_array['rightsLevel'],
    rightsText=json_array['rightsText'],
    text=json_array['text'],
    author=json_array['author'],
    pubDate=json_array['pubDate'],
    relDate=json_array['relDate'],
    modDate=json_array['modDate'],
    archiveUrl=json_array['archiveUrl'],
    downloadUrl=json_array['downloadUrl'],
    storeUrl=json_array['storeUrl'],
    html=json_array['html'], 
    genre=json_array['genre'], 
    title=json_array['title'], 
    size=json_array['size'], 
    fileType=json_array['fileType'], 
    kind=json_array['kind'], 
    icon= json_array['icon']
    )
  i.setHashId()
