# 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

from typing import Tuple

from bpy.types import UILayout

from ..operators.support_assign_material import UI_OT_support_assign_material
from ..operators.create_node_vertex_colors import UI_OT_create_vertex_colors
from ..operators.support_set_vertex_colors import UI_OT_support_set_vertex_colors
from ..operators.support_generate_previews import UI_OT_support_generate_previews
from ..operators.support_multi_purpose import UI_OT_multi_purpose
from ..registries.texture_registry import RepositoryType, TextureEntry
from ..properties import BaseMappingProperties, Properties
from ..preferences import PreferencesPanel


def insert_preview_update(layout: UILayout, type: RepositoryType, categories: str):
    """
    Show create/update previes operator in given layout.
    """
    op = layout.operator(
        UI_OT_support_generate_previews.bl_idname,
        text='Create or update ALL previews',
        icon='FILE_REFRESH'
    )
    op.repository_type = type
    op.category = categories
    op.missing_only = False
    op.size = PreferencesPanel.get().preview_render_size
    op = layout.operator(
        UI_OT_support_generate_previews.bl_idname,
        text='Create or update missing previews',
        icon='FILE_REFRESH'
    )
    op.repository_type = type
    op.category = categories
    op.missing_only = True
    op.size = PreferencesPanel.get().preview_render_size


def insert_category_and_preview(layout: UILayout, scale: float, scale_popup: float, prop: BaseMappingProperties):
    """
    Add category and preview selector into UI layout.
    """
    if prop.get_categories():
        layout.row(align=True).prop(prop, 'categories')
        if prop.get_previews():
            layout.row(align=True).template_icon_view(
                prop, 
                'previews', 
                show_labels=True, 
                scale=scale, 
                scale_popup=scale_popup
            )    
        else:
            layout.label(text='No content')
    else:
        layout.label(text='No categories')


def insert_brush(layout: UILayout, entry: TextureEntry, include_favourite: bool, is_favourite: bool, tool_mode: str):
    """
    Brush select control with optional favourite switch.
    """
    b = layout.box().column(align=True)
    b.template_icon(icon_value=entry.preview_icon_id, scale=3)
    r = b.row(align=True)
    op = r.operator('snw.support_select_brush', text='', icon='IMAGE_DATA')
    op.bin_hash = entry.get_bin_hash()
    op.mode = 'sRGB'
    op.tool_mode = tool_mode
    op = r.operator('snw.support_select_brush', text='', icon='NODE_COMPOSITING')
    op.bin_hash = entry.get_bin_hash()
    op.mode = 'Non-Color'
    op.tool_mode = tool_mode

    if include_favourite:
        op = r.operator('snw.support_select_brush', text='', icon='FAKE_USER_ON' if is_favourite else 'FAKE_USER_OFF')
        op.bin_hash = entry.get_bin_hash()
        op.mode = 'Fav-' if is_favourite else 'Fav+'
        op.tool_mode = tool_mode


def insert_set_vertex_colors(l: UILayout, text: str, icon: str, mode: str, seed: int, col: Tuple[float, float, float, float]):
    """
    Calls set vertex color op with different parameters, used from pie and side panel.
    """
    props = Properties.get()

    if icon:
        op = l.operator(UI_OT_support_set_vertex_colors.bl_idname, text=text, icon=icon) # type: UI_OT_support_set_vertex_colors
    else:
        op = l.operator(UI_OT_support_set_vertex_colors.bl_idname, text=text) # type: UI_OT_support_set_vertex_colors
    op.mode = mode
    op.cols = props.vertex_color_set
    op.selection = props.vertex_select
    op.seed = seed
    op.col = col
    op.final_mode = 'EDIT'   


def insert_vertex_color_panel(l: UILayout, context: bpy.types.Context):
    """
    The complete vertex color control panel, used in pie and side panel.
    """
    props = Properties.get()
    obj = context.active_object

    l.operator(UI_OT_create_vertex_colors.bl_idname, text='New', icon='ADD')            
    if obj.data.vertex_colors:
        l.prop(props, 'vertex_color_set', text='')
        l.separator()
        l.prop(props, 'vertex_select', toggle=True, icon='FACESEL')
        l.separator()
        s = l.split(factor=0.9, align=True)
        insert_set_vertex_colors(s, 'Color', 'COLOR', 'CC', 0, props.vertex_color)
        s.prop(props, 'vertex_color', text='')
        insert_set_vertex_colors(l, 'Random Per Island', 'FACE_MAPS', 'PI', props.vertex_seed, (0, 0, 0, 0))
        insert_set_vertex_colors(l, 'Random Per Face', 'OUTLINER_DATA_POINTCLOUD', 'RPV', props.vertex_seed, (0, 0, 0, 0))
        l.prop(props, 'vertex_seed')              
        l.separator()
        ro = l.row(align=True)
        for i in range(5):
            insert_set_vertex_colors(ro, f'T{i + 1}', None, 'CC', 0, (0.25 * i, 0.25 * i, 0.25 * i, 1.0))


def insert_material_assign_menu(l: UILayout, context: bpy.types.Context):
    UI_OT_support_assign_material.create_ui(l, 'New Material', 'ADD', -1, None)
    for material in bpy.data.materials:
        if material.preview:
            UI_OT_support_assign_material.create_ui(l, material.name_full, None, material.preview.icon_id, material)
        else:
            UI_OT_support_assign_material.create_ui(l, material.name_full, 'QUESTION', -1, material)



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='Shader Node Wizard - Trial Ended', icon='INFO')
    elif ex < 3:
        c.label(text='Shader Node Wizard - Trial Ended', icon='TIME')
    elif ex < 7:
        c.label(text='Shader Node Wizard - Trial Ended (Again)', icon='QUESTION')
    else:
        c.label(text='Shader Node Wizard - Still Trialing?', icon='HEART')

    c.separator()
    c.label(text='Thanks for trying Shader Node Wizard!')

    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 SNW is right for you.',
            ]
        elif ex == 1:
            intro_texts = [
                'Thanks for trying Shader Node Wizard!',
                '',
                '🎁 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 SNW 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 SNW 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',
                'SNW 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, SNW is worth the $24.95.',
                '',
                'Support continued development!',
            ]

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

        c.separator()
        UI_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 Shader Node Wizard!',
                '',
                '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 SNW',
                '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 SNW 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()
        UI_OT_multi_purpose.create_ui_buy(c, False)            