# Copyright (C) 2022 Thomas Hoppe (h0bB1T). All rights reserved.
#
# Unauthorized copying of this file via any medium is strictly prohibited.
# Proprietary and confidential.

import bpy, os

from bpy.types import UILayout

from typing import List, Tuple, Union


from ..properties import PropertySection, Properties
from ..utils.blender import all_spaces
from ..registries.resource_lists_registry import ResourceListsRegistry
from ..registries.config_registry import ConfigRegistry
from ..operators.multi_purpose import ASSET_OT_multi_purpose
from ..operators.tag_manager import ASSET_OT_tag_manager
from ..operators.export_assets import ASSET_OT_export
from ..operators.refresh_res_list import ASSET_OT_refresh_res_lists
from ..operators.create_new_blend import ASSET_OT_create_new_blend
from ..operators.create_catalog import ASSET_OT_create_catalog


def initial_info(l: UILayout):
    c = l.column(align=True)
    c.label(text='! NOTICE !', icon='ERROR')
    c.separator()
    for t in [
            'Despite Asset Wizard Pro has been',
            'tested, exporting Assets into', 
            'existing .blend Files was not', 
            'straightforward, as it is not',
            'directly possible with Blender\'s API.',
            'So please make a Backup of Library', 
            'Files, to which you like to add Assets.',
            '',
            'I\'m not responsible for data', 
            'losses when ignoring this Advice.',
            'Backups are recommended in any way.'
        ]:
        c.label(text=t)

    c.separator()
    ASSET_OT_multi_purpose.create_ui_agree(c)



def export_panel(
    l: UILayout, 
    res: List[Tuple[str, str, str, str]], 
    section: PropertySection, 
    section_name: str
    ) -> Union[UILayout, None]:
    """
    Common UI for export used in Shader and Geometry Node space, as well as in 3D view.
    Returns column layout if export is possible, otherwise None
    """
    props = Properties.get()

    if ConfigRegistry.get().show_initial_info():
        return initial_info(l)

    c = l.column(align=True)
    c.use_property_decorate = False
    c.use_property_split = True
    if bpy.context.preferences.filepaths.asset_libraries:
        # Is there any file in this repo?
        if ResourceListsRegistry.get().library_files(section.export_library):
            r = c.row(align=True)
            r.label(text='Export to:', icon='EXPORT')
            if ResourceListsRegistry.get().library_files(section.export_library):
                r.prop(section, 'show_stats', text='', icon='QUESTION', toggle=True)
                ASSET_OT_multi_purpose.create_ui_open_asset(r, os.path.join(section.export_library, section.export_file))
            ASSET_OT_refresh_res_lists.create_ui(r)
            if all_spaces('FILE_BROWSER'):
                ASSET_OT_multi_purpose.create_ui_refresh_lib(r)     
            s = c.split(factor=0.3, align=True)
            s.prop(section, 'export_library_back', text='')
            r = s.row(align=True)
            r.prop(section, 'export_file_back', text='')
            ASSET_OT_create_new_blend.create_ui(r, section.export_library, section_name, True)

            s = c.row(align=True)# c.split(factor=0.9, align=True)
            if ResourceListsRegistry.get().catalogs(section.export_library):
                s.prop(section, 'catalog_back', text='')
            else:
                s.box().label(text='Repository has no Catalog yet')
            ASSET_OT_create_catalog.create_ui(s, section_name)                       

            # File statistics.
            if section.show_stats:
                b = c.box().column()
                for e, t in ResourceListsRegistry.get().stats(os.path.join(section.export_library, section.export_file)):
                    b.label(text=f'{e}: {t}')

            c.separator()

            # Catalog, tags, description author.
            c.prop(section, 'description', text='Description')
            c.prop(props, 'author', text='Author')
            c.prop(section, 'use_render_as_preview', toggle=True, text='Render Result', icon='RENDER_STILL')

            if ConfigRegistry.get().tags():
                s = c.row(align=True) #c.split(factor=0.9, align=True)
                s.prop(section, 'tag_select_back', text='Tag')
                ASSET_OT_tag_manager.create_ui(s, 'ADD', True, 'ADD', section_name, section.tag_select)

            s = c.row(align=True) #c.split(factor=0.9, align=True)
            s.prop(section, 'new_tag', text='New Tag')
            ASSET_OT_tag_manager.create_ui(
                s, 
                'ADD', 
                len(section.new_tag) > 0,
                'ADD_NEW',
                section_name,
                section.new_tag
            )

            c.separator()
            b = c.box().column(align=True)
            if section.tags:
                for t in section.tags:
                    s = b.split(factor=0.9, align=True)
                    s.label(text=t.title)
                    ASSET_OT_tag_manager.create_ui(s, 'REMOVE', True, 'REMOVE', section_name, t.title)
            else:
                b.label(text='No Tags selected')

            c.separator()
            for mitn in res:
                ASSET_OT_export.create_ui(c, mitn, section)

            return c
        else:
            s = c.split(factor=0.4, align=True)
            ASSET_OT_create_new_blend.create_ui(s, section.export_library, section_name)
            c.box().label(text='No File in Library, create one', icon='ERROR')
    else:
        b = c.box()
        b.label(text='No Asset Libraries configured,')
        b.label(text='check Preferences')


def trial_panel(l: UILayout):
    from ..utils.tools import local_addon_info

    ex = local_addon_info.ex

    c = l.column(align=True)
    if ex == 0:
        c.label(text='Asset Wizard Pro - Trial Ended', icon='INFO')
    elif ex < 3:
        c.label(text='Asset Wizard Pro - Trial Ended', icon='TIME')
    elif ex < 7:
        c.label(text='Asset Wizard Pro - Trial Ended (Again)', icon='QUESTION')
    else:
        c.label(text='Asset Wizard Pro - Still Trialing?', icon='HEART')

    c.separator()
    c.label(text='Thanks for trying Asset Wizard Pro!')

    if local_addon_info.cxp():
        if ex == 0:
            intro_texts = [
                '🎁 One more day? No problem!',
                '',
                'You can extend the trial for 24 hours',
                'anytime you want. Take your time to',
                'decide if AWP is right for you.',
            ]
        elif ex == 1:
            intro_texts = [
                'Thanks for trying Asset Wizard Pro!',
                '',
                '🎁 Need another day? Sure!',
                '',
                'You can extend for 24 hours again.',
                'No pressure - evaluate at your own pace.',
            ]
        elif ex == 2:
            intro_texts = [
                'Welcome back!',
                '',
                'You can extend for another 24 hours.',
                '',
                '💡 If you\'re using AWP regularly,',
                'consider unlocking it permanently.',
            ]
        elif ex < 5:
            intro_texts = [
                f'Extension #{ex + 1}',
                '',
                'You can extend for 24h again.',
                '',
                f'💭 You\'ve extended {ex} times now.',
                'Looks like AWP is useful to you!',
                '',
                'Why not unlock it permanently?',
            ]
        elif ex < 7:
            intro_texts = [
                'Still here? That\'s great! 😊',
                '',
                f'You can extend for 24h (Extension #{ex + 1})',
                '',
                '💡 Quick math:',
                f'You\'ve extended {ex} times = {ex} days of use.',
                'For $24.95, you get lifetime access.',
                '',
                'That\'s less than $1 per day so far!',
            ]
        elif ex < 10:
            intro_texts = [
                f'Extension #{ex + 1} - We meet again! 😄',
                '',
                'You can extend for another 24h.',
                '',
                '🤔 At this point, you\'re clearly using',
                'AWP regularly. Why not just unlock it?',
                '',
                '$24.95 < constantly clicking "Extend"',
            ]
        else:
            intro_texts = [
                f'OK, this is Extension #{ex + 1}... 😅',
                '',
                'You can still extend for 24h.',
                '(I respect the dedication!)',
                '',
                '💰 But seriously: If you\'re extending',
                'this often, AWP is worth the $24.95.',
                '',
                'Support continued development!',
            ]

        for t in intro_texts:
            if t == '':
                c.separator()
            else:
                c.label(text=t)

        c.separator()
        ASSET_OT_multi_purpose.create_ui_buy(c, True)
    else:
        nx_ps = local_addon_info.exp()
        h, m = divmod(nx_ps // 60, 60)
        nx_ps_t = f'{int(h)}h {int(m)}m'

        if ex == 0:
            wait_texts = [
                'Thanks for trying Asset Wizard Pro!',
                '',
                'The 14-day trial has ended.',
                '',
                '⏰ You can extend for 24h again',
                f'   in {nx_ps_t}',
                '',
                'Or purchase now for permanent access.',
            ]
        elif ex < 3:
            wait_texts = [
                'Trial extension ended.',
                '',
                f'⏰ Next extension available in {nx_ps_t}',
                '',
                'Or purchase now to use AWP',
                'without interruptions.',
            ]
        elif ex < 5:
            wait_texts = [
                'Extension ended.',
                '',
                f'⏰ Next extension in {nx_ps_t}',
                '',
                f'💭 You\'ve extended {ex} times.',
                'Enjoying the features? Consider',
                'purchasing for uninterrupted access.',
            ]
        elif ex < 7:
            wait_texts = [
                'Extension ended (again).',
                '',
                f'⏰ Next extension in {nx_ps_t}',
                '',
                f'💡 {ex} extensions so far!',
                'If AWP is part of your workflow,',
                'unlock it permanently for $24.95.',
                '',
                'No more waiting. No more interruptions.',
            ]
        else:
            wait_texts = [
                f'Extension #{ex} ended. 😊',
                '',
                f'⏰ Next extension in {nx_ps_t}',
                '',
                '🤔 You\'ve been doing this for a while!',
                'At some point, just buying it is',
                'easier than this every-other-day dance.',
                '',
                'Just saying... 😄',
            ]
        
        for t in wait_texts:
            if t == '':
                c.separator()
            else:
                c.label(text=t)

        c.separator()
        ASSET_OT_multi_purpose.create_ui_buy(c, False)

