import bpy
from bpy.props import IntProperty, StringProperty

from .config import ADDON_SERVICE_URL, __addon_name__
from .credential_store import storage_description


DEFAULT_SERVICE_URL = ADDON_SERVICE_URL


class THREEDRIPPER_HELPER_Preferences(bpy.types.AddonPreferences):
    bl_idname = __addon_name__

    service_url: StringProperty(
        name="3DRipper service URL",
        description="Account and entitlement service used by the official Add-on",
        default=DEFAULT_SERVICE_URL,
    )
    request_timeout: IntProperty(
        name="Network timeout (seconds)",
        description="Maximum time to wait for login and entitlement requests",
        default=8,
        min=2,
        max=30,
    )

    def draw(self, _context):
        layout = self.layout
        layout.prop(self, "service_url")
        layout.prop(self, "request_timeout")
        layout.separator()
        layout.label(text="Access tokens are stored in {}.".format(storage_description()))


def get_addon_preferences(context=None):
    current_context = context or bpy.context
    addon = current_context.preferences.addons.get(__addon_name__)
    return addon.preferences if addon else None
