"""Independent presentation modules for the single skin.milionar addon."""
import os

from wcs.skin import compose

MENU = 'skin_menu_layout'
MATERIAL = 'skin_material'
APPLIED = 'skin_appearance_applied'
# Explicit asset names let the runtime packager retain all four previews.
PREVIEWS = {
    ('sidebar', 'normal'): 'sidebar-normal.png',
    ('sidebar', 'glass'): 'sidebar-glass.png',
    ('horizontal', 'normal'): 'horizontal-normal.png',
    ('horizontal', 'glass'): 'horizontal-glass.png',
}


def choices(addon):
    menu = addon.getSetting(MENU)
    material = addon.getSetting(MATERIAL)
    return (menu if menu in ('sidebar','horizontal') else 'sidebar',
            material if material in ('normal','glass') else 'glass')


def key(addon):
    return ':'.join(choices(addon))


def plan(resources, menu='sidebar', material='glass', order=''):
    if menu not in ('sidebar','horizontal') or material not in ('normal','glass'):
        raise ValueError('invalid appearance module')
    modules=os.path.join(resources,'skin-modules')
    planned = compose.plan(os.path.join(resources,'skin.milionar'),
                        os.path.join(modules,'materials',material),
                        layers=(os.path.join(modules,'shared'),os.path.join(modules,'layouts',menu)))
    if order:
        from wcs.skin import menu_order
        home = os.path.join('xml', 'Home.xml')
        source, transform = planned[home]
        planned[home] = (source, lambda data: menu_order.reorder(transform(data) if transform else data, order))
    return planned


def write(resources, target, menu='sidebar', material='glass', order=''):
    written=[]
    for name,entry in plan(resources,menu,material,order=order).items():
        destination=os.path.join(target,name);data=compose.read(entry)
        try:
            with open(destination,'rb') as handle:
                if handle.read()==data:continue
        except OSError:pass
        os.makedirs(os.path.dirname(destination),exist_ok=True)
        with open(destination,'wb') as handle:handle.write(data)
        written.append(name)
    return written
