# Copyright (c) 2017 Adler Neves <adlerosn@gmail.com>
#
# MIT License
#
# 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 logging
logger = logging.getLogger(__name__)

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRETS_DIR = os.path.join(BASE_DIR,'server_secrets')

PLUGINS_DIR = os.path.join(BASE_DIR,'plugins')

# PGN = os.path.join(SECRETS_DIR,'PLUGINS.lst')
#
# if not os.path.exists(PGN):
#     with open(PGN,'wt') as f:
#         f.write('')
#
# PLUGINS = list()
# with open(PGN,'rt') as f:
#     PLUGINS = f.read().strip().splitlines()

availablePlugins = dict()
enabledPlugins = dict()

pluginToDirectory = dict()

for plugin_dir in sorted(os.listdir(PLUGINS_DIR)):
    if plugin_dir in ['_template','__init__.py','__pycache__']: continue
    plugin_pkg = 'plugins.'+plugin_dir
    plugin_dir = os.path.join(PLUGINS_DIR,plugin_dir)
    if not os.path.isdir(plugin_dir): continue
    try:
        exec('import %s; availablePlugins["%s"] = %s'%(plugin_pkg,plugin_pkg,plugin_pkg))
        pluginToDirectory[plugin_pkg] = plugin_dir
        logger.warn("[PLUGIN][INIT][SUCCESS] '%s' seems importable"%plugin_pkg)
    except:
        logger.critical("[PLUGIN][INIT][ERROR][NONFATAL] '%s' couldn't be imported"%plugin_pkg)

# for wantedPluginName in PLUGINS:
#     if wantedPluginName not in availablePlugins:
#         logger.error("[PLUGIN][INIT][ERROR][NONFATAL] '%s' is to be loaded, but not installed"%wantedPluginName)
#     else:
#         enabledPlugins[wantedPluginName] = availablePlugins[wantedPluginName]

enabledPlugins = availablePlugins

enabledPluginsTemplatesDir = list()

for plg_pkg, plg_mod in sorted(enabledPlugins.items()):
    plg_dir = pluginToDirectory[plg_pkg]
    enabledPluginsTemplatesDir.append(os.path.join(plg_dir, 'templates'))

enabledPluginsTemplatesDir.sort()

pluginUrlImport = '#!/usr/bin/env python3'
pluginUrlImport+= '\n'
pluginUrlImport+= '# -*- encoding: utf-8 -*-'
pluginUrlImport+= '\n'
pluginUrlImport+= '#Autogenerated'
pluginUrlImport+= '\n'
pluginUrlImport+= '\n'
pluginUrlImport+= 'from django.conf.urls import url'
pluginUrlImport+= '\n'
pluginUrlImport+= 'from django.conf.urls import include'
pluginUrlImport+= '\n'
pluginUrlImport+= '\n'
for plg_pkg, plg_mod in sorted(enabledPlugins.items()):
    pluginUrlImport+='''import %s.urls'''%(plg_pkg)
    pluginUrlImport+='\n'
pluginUrlImport+= '\n'
pluginUrlImport+= 'urlpatterns = ['
pluginUrlImport+= '\n'
for plg_pkg, plg_mod in sorted(enabledPlugins.items()):
    pluginUrlImport+=' '*4
    pluginUrlImport+='''url(r'^%s/', include(%s.urls)),'''%(plg_pkg.split('.')[-1],plg_pkg)
    pluginUrlImport+='\n'
pluginUrlImport+= ']\n'

with open(os.path.join(SECRETS_DIR,'pluginUrls.py'), 'w') as f:
    f.write(pluginUrlImport)

analysisHandlersImport = '#!/usr/bin/env python3'
analysisHandlersImport+= '\n'
analysisHandlersImport+= '# -*- encoding: utf-8 -*-'
analysisHandlersImport+= '\n'
analysisHandlersImport+= '#Autogenerated'
analysisHandlersImport+= '\n'
analysisHandlersImport+= '\n'
for plg_pkg, plg_mod in sorted(enabledPlugins.items()):
    analysisHandlersImport+='''import %s.hooks'''%(plg_pkg)
    analysisHandlersImport+='\n'
analysisHandlersImport+= '\n'
analysisHandlersImport+= 'hookModules = ['
analysisHandlersImport+= '\n'
for plg_pkg, plg_mod in sorted(enabledPlugins.items()):
    analysisHandlersImport+=' '*4
    analysisHandlersImport+='%s.hooks,'%(plg_pkg)
    analysisHandlersImport+='\n'
analysisHandlersImport+= ']\n'

with open(os.path.join(SECRETS_DIR,'hookModules.py'), 'w') as f:
    f.write(analysisHandlersImport)

logger.warn('[PLUGIN] Initialization script complete')
