"""
“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
from pathlib import Path

BASE_DIR = os.path.abspath(
                        os.path.join(
                            os.path.dirname(os.path.realpath(__file__)),
                            '../')
                        )
OBJECT_DIR = os.path.join(BASE_DIR, 'objects')
OBJECT_TYPES = ['gltf', 'glb', 'obj', 'fbx', 'stl', 'dae', 'json', 'ply']

def get_directory_content(dir_path):
    content = []
    for p in Path(dir_path).iterdir():
        file = Path(p)
        if file.name.startswith("."):
            continue
        model_type = (Path(file.name).suffix).lstrip('.').lower()
        is_object_file = True if model_type in OBJECT_TYPES else False
        item = {
                'name': os.path.basename(p),
                'size': human_readable_bytes(os.path.getsize(p)),
                'is_dir': True if p.is_dir() else False,
                'is_object_file': is_object_file
        }
        content.append(item)
    return content


def find_skybox_image(dir):
    for p in Path(dir).iterdir():
        extension = Path(p).suffix
        if str(Path(p)).endswith(f"sky-box-image{extension}"):
            return str(p)
    return None

def find_pre_loader_image(dir):
    for p in Path(dir).iterdir():
        extension = Path(p).suffix
        if str(Path(p)).endswith(f"pre-load-image{extension}"):
            return str(p)
    return None

def find_file_with_extension(dir, extension):
    for p in Path(dir).iterdir():
        if Path(p).suffix.lstrip('.').lower() == extension:
            return str(p).replace(OBJECT_DIR, "")
    return None


def get_object(file_path, result={}):
    parts = file_path.split('/')
    file_name = parts.pop()
    file_dir = os.path.join(OBJECT_DIR, *parts)

    print('get_object(file_dir): ', file_dir)
    print('get_object(file_name): ', file_name)
    print('get_object(file_path): ', os.path.join(OBJECT_DIR, *parts, file_name))
    if not os.path.exists(os.path.join(OBJECT_DIR, *parts, file_name)):
        print("cant find file")
        return result

    if not result:
        result['urls'] = []
        result['type'] = None
    extension = Path(file_name).suffix.lstrip('.').lower()
    print('get_object(extension):', extension)

    if extension == "gltf" or extension == 'glb':
        if extension == "gltf":
            result['type']="gltf"
        if extension == 'glb':
            result['type'] = "glb"
        object_path = str(file_path).replace(OBJECT_DIR, "")
        result['urls'].append(f"/objects/{object_path}")
        skybox_path = find_skybox_image(file_dir)
        if skybox_path:
            skybox_path = str(skybox_path).replace(OBJECT_DIR, '')
            result['skybox'] = f"/objects{skybox_path}"
        preloader_path = find_pre_loader_image(file_dir)
        if preloader_path:
            preloader_path = str(preloader_path).replace(OBJECT_DIR, '')
            result['preloader'] = f"/objects{preloader_path}"
        return result
    if extension == "obj":
        result['type']="obj"
        object_path = str(file_path).replace(OBJECT_DIR, "")
        result['urls'].append(f"/objects{object_path}")
        mtl_file = find_file_with_extension(file_dir, 'mtl')
        if mtl_file:
            result = get_object(mtl_file.replace(OBJECT_DIR, ""), result)
            result['type']="obj-mtl"
        return result
    if extension == 'stl':
        result['type'] = "stl"
        object_path = str(file_path).replace(OBJECT_DIR, "")
        result['urls'].append(f"/objects/{object_path}")
        return result
    if extension == 'mtl':
        object_path = str(file_path).replace(OBJECT_DIR, "")
        result['urls'].append(f"/objects/{object_path}")
        return result
    if extension == 'fbx':
        result['type'] = "fbx"
        object_path = str(file_path).replace(OBJECT_DIR, "")
        result['urls'].append(f"/objects/{object_path}")
        return result
    if extension == 'dae':
        result['type'] = "dae"
        object_path = str(file_path).replace(OBJECT_DIR, "")
        result['urls'].append(f"/objects/{object_path}")
        return result
    if extension == 'json':
        result['type'] = "json"
        object_path = str(file_path).replace(OBJECT_DIR, "")
        result['urls'].append(f"/objects/{object_path}")
        return result
    if extension == 'ply':
        result['type'] = "ply"
        object_path = str(file_path).replace(OBJECT_DIR, "")
        result['urls'].append(f"/objects/{object_path}")
        return result
    return None


"""
    if 'obj' in extensions and 'mtl' in extensions:
        print("p: ",p)
        return 'obj-mtl'
    if 'obj' in extensions:
        return 'obj'
    if 'gltf' in extensions:
        return 'gltf'
    if 'fbx' in extensions:
        return 'fbx'
    if 'stl' in extensions:
        return 'stl'
"""

def human_readable_bytes(bytes):
    """ 1 KibiByte == 1024 Bytes
        1 Mebibyte == 1024*1024 Bytes
        1 GibiByte == 1024*1024*1024 Bytes
    """
    if bytes == 0:
        return "0 bytes"
    if bytes < 1024:
         return f"{bytes} bytes"
    if bytes < 1024*1024:
        return f"{int(round(bytes/(1024), 2))} KB"
    if bytes < 1024*1024*1024:
        return f"{int(round(bytes/(1024*1024), 2))} MB"
    return f"{int(round(bytes/(1024*1024*1024), 2))} GB"
