
"""
Plugin for making an asset library of all  blender file found in a folder
"""

import os
import re
import uuid
import shutil
import json
import requests
import urllib3
import traceback
import time
from itertools import groupby
from pathlib import Path
from pprint import pprint as pp

import bpy
from bpy.props import (StringProperty, IntProperty, BoolProperty, EnumProperty)

from .library_plugin import LibraryPlugin
from ..core.template import Template
from ..core.file_utils import install_module


REQ_HEADERS = requests.utils.default_headers()
REQ_HEADERS.update({"User-Agent": "Blender: PH Assets"})

class PolyHaven(LibraryPlugin):

    name = "Poly Haven"
    # template_name : StringProperty()
    # template_file : StringProperty()
    directory : StringProperty(subtype='DIR_PATH')
    asset_type : EnumProperty(items=[(i.replace(' ', '_').upper(), i, '') for i in ('HDRIs', 'Models', 'Textures')], default='HDRIS')
    main_category : StringProperty(
        default='artificial light, natural light, nature, studio, skies, urban'
    )
    secondary_category : StringProperty(
        default='high constrast, low constrast, medium constrast, midday, morning-afternoon, night, sunrise-sunset'
    )

    #blend_depth: IntProperty(default=1)

    # url: StringProperty()
    # login: StringProperty()
    # password: StringProperty(subtype='PASSWORD')
    # project_name: StringProperty()
    
    def get_asset_path(self, name, catalog, directory=None):
        # chemin: Source, Asset_type, asset_name / asset_name.blend -> PolyHaven/HDRIs/test/test.blend
        directory = directory or self.source_directory
        catalog = self.norm_file_name(catalog)
        name = self.norm_file_name(name)

        return Path(directory, self.get_asset_relative_path(name, catalog))

    # def bundle(self, cache_diff=None):
    #     """Group all asset in one or multiple blends for the asset browser"""

    #     return super().bundle(cache_diff=cache_diff)

    def format_asset_info(self, asset_info, asset_path):
        #  prend un asset info et output un asset description

        asset_path = self.prop_rel_path(asset_path, 'source_directory')
        modified = asset_info.get('modified', time.time_ns())

        return dict(
            filepath=asset_path,
            modified=modified,
            library_id=self.library.id,
            assets=[dict(
                catalog=asset_data.get('catalog', asset_info['catalog']),
                author=asset_data.get('author'),
                metadata=asset_data.get('metadata', {}),
                description=asset_data.get('description', ''),
                tags=asset_data.get('tags', []),
                type=self.data_type,
                image=self.template_image,
                video=self.template_video,
                name=asset_data['name']) for asset_data in asset_info['assets']
            ]
        )
        
    def fetch(self):
        """Gather in a list all assets found in the folder"""

        print(f'Fetch Assets for {self.library.name}')
        
        print('self.asset_type: ', self.asset_type)
        url = f"https://api.polyhaven.com/assets?t={self.asset_type.lower()}"
        # url2 = f"https://polyhaven.com/{self.asset_type.lower()}"
        # url += "&future=true" if early_access else ""
        # verify_ssl = not bpy.context.preferences.addons["polyhavenassets"].preferences.disable_ssl_verify
        
        verify_ssl = False
        try:
            res = requests.get(url, headers=REQ_HEADERS, verify=verify_ssl)
            res2 = requests.get(url2, headers=REQ_HEADERS, verify=verify_ssl)
        except Exception as e:
            msg = f"[{type(e).__name__}] Error retrieving {url}"
            print(msg)
            # return (msg, None)

        if res.status_code != 200:
            error = f"Error retrieving asset list, status code: {res.status_code}"
            print(error)
            # return (error, None)
        
        catalog = None

        # return (None, res.json())
        for asset_info in res.json().values():
            main_category = None
            secondary_category = None
            for category in asset_info['categories']:
                if category in self.main_category and not main_category:
                    main_category = category
                if category in self.secondary_category and not secondary_category:
                    secondary_category = category
            
            if main_category and secondary_category:
                catalog = f'{main_category}_{secondary_category}'

            if not catalog:
                return

            asset_path = self.get_asset_path(asset_info['name'], catalog)
            print('asset_path: ', asset_path)
            asset_info = self.format_asset_info(asset_info, asset_path)
            print('asset_info: ', asset_info)

        # return self.format_asset_info([asset['name'], self.get_asset_path(asset['name'], catalog) for asset, asset_infos in res.json().items()]) 
        # pp(res.json())
        # pp(res2.json())
        # print(res2)


        # return asset_infos
