import json
from DateTime import DateTime

portal = context.getPortalObject()
preference_tool = portal.portal_preferences
software_product_list = portal.portal_catalog(portal_type='Software Product', validation_state='validated')
appstore_data = []
logo_url_list = []
i = 0

def getManifestData(version):
  doc = portal.portal_catalog.getResultValue(
    portal_type="File",
    version=version
  )
  if not doc:
    return
  try:
    json_doc = json.loads(doc.getData())[0]
  except ValueError:
    return
  logo_src = ""
  if json_doc.has_key('logo') and isinstance(json_doc['logo'], dict):
    logo_src = json_doc['logo'].get('url', '')
  return {
    "short_name": json_doc['title'],
    "name": json_doc['title'],
    "filename": doc.getFilename(),
    "description": json_doc['description'],
    "icons": [{
      "src": logo_src,
      "sizes": "128x128",
      "type": "image/png"
    }],
    "start_url": "../../",
    "display": "standalone"
  }

for software_product in software_product_list:
  web_site = software_product.SoftwareProduct_getRelatedWebSite()
  version = web_site.getLayoutProperty('configuration_latest_version')
  # allow to have application without web manifest
  data = getManifestData(version)
  logo = None
  if data is not None:
    src_icon = data['icons'][0]['src']
    logo_src = None
    if src_icon == '':
      logo = portal.portal_catalog.getResultValue(reference='default_web_site_logo.png', portal_type='File')
    elif src_icon.startswith('data:image'):
      logo_src = src_icon
    else:
      logo = portal.portal_catalog.getResultValue(reference='%' + src_icon, version=version, portal_type='File')
    if logo is not None:
      logo_src = logo.getReference()
      logo_url_list.append('appstore/' + logo_src)
    if logo_src is not None:
      # Future domain could be defined by user
      app_domain = software_product.getFollowUpId(portal_type="Web Section")
      appstore_data.append({
        "int_index": str(i),
        "application_image_type": 'image',
        "application_image_url": logo_src,
        "application_toc_accept": 'true',
        "application_published": 'some_date',
        "application_submitted": 'other_date',
        "application_description": data["description"] if "description" in data else data["name"],
        "application_url": "https://mynij.app.officejs.com/#/?page=load_source&url=%s://%s/%s/%s/%s" % (
                            preference_tool.getPreferredSystemAppstoreWildcardProtocol(),
                            preference_tool.getPreferredSystemAppstoreWildcardDomain(),
                            app_domain,
                            version,
                            data['filename']
                          ),
        "application_title": data["short_name"],
        "application_category": data['category'] if "category" in data else "Documents",
        "application_title_i18n": "application.custom.%s.title" % app_domain,
        "application_description_i18n": "application.custom.%s.description" % app_domain
      })
      i+=1

json_data = json.dumps(appstore_data)
json_document = portal.document_module['store_officejs_data_application_sample_json']

if (json_data != json_document.getData()):
  # Do not modify document history with edit if nothing changed
  json_document.edit(data=json.dumps(appstore_data))
  manifest_content = portal.web_page_module['store_officejs_base_appcache'].getTextContent()
  # Ensure the appcache content is modified when the json is too
  logo_url_list.append('# %s' % DateTime())
  portal.web_page_module['store_officejs_appcache'].edit(text_content=manifest_content.replace('${logo_list}', '\n'.join(logo_url_list)))
