"""
“Copyright 2021 Hangar.org”

This file is part of 3D-tester.

3D-tester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""


import os, sys
from pathlib import Path
import bottle
from bottle import route, run, error, abort, template, response, static_file
from utils.utils import BASE_DIR, OBJECT_DIR
from utils import utils


@route('/static/<filename:path>', name='static')
def serve_static(filename):
    return static_file(filename, root=os.path.join(BASE_DIR, 'static'))

@route('/vendor/<filename:path>', name='static')
def serve_static(filename):
    return static_file(filename, root=os.path.join(BASE_DIR, 'vendor'))

@route('/objects/<filename:path>', name='static')
def serve_static(filename):
    return static_file(filename, root=os.path.join(BASE_DIR, 'objects'))


@route('/')
@route('/list')
@route('/list/')
def index():
    content = utils.get_directory_content(OBJECT_DIR)
    return template('list-dir',
                    parent_dir="",
                    current_dir="",
                    content=content)

@route('/list/<dir_path:path>')
def list_dir(dir_path):
    print("list path: ",dir_path)
    #dir_path = dir_path.replace('/list/', '')
    parts = dir_path.split('/')
    print("list path: ",dir_path)
    current_dir=os.path.join(OBJECT_DIR, *parts)
    content = utils.get_directory_content(current_dir)
    parts.pop()
    parent_dir='/'.join(parts) if parts else ""
    return template('list-dir',
                    parent_dir=parent_dir,
                    current_dir=dir_path.rstrip('/'),
                    content=content)

@route('/render/<file_path:path>')
def render(file_path):
    file_path = file_path.replace('/render/', '')
    parts = file_path.split('/')
    file_name = parts.pop()
    file_dir = os.path.join(OBJECT_DIR, *parts)

    #print("file_dir: ", file_dir)
    #print("file_name: ", file_name)

    object = utils.get_object(file_path, {})
    if not object:
        return "Opps, no object type"

    print("object: ", object)
    if object['type'] == 'gltf' or object['type'] == 'glb':
        page_tpl = "google"
    else:
        page_tpl = "vue-3d"

    return template(page_tpl,
                    current_dir=file_path.replace(file_name, ""),
                    name=file_name,
                    object=object,
                )

if __name__ == "__main__":
    run(host='localhost', port=8080, debug=True)

app = bottle.default_app()
