#!/usr/bin/env python3
"""Generate a theme for Chrome based on the palatte generated by wal."""
import json
import subprocess
import shlex
import sys
from pywal.settings import CACHE_DIR
import collect
import tint

CONFIG_DIR = collect.Path('~/.config/wal')
CACHE_DIR = collect.Path(CACHE_DIR)
THEME_DIR = CACHE_DIR / 'wal_chrome'

Logger = collect.Logger
Logger.name += '.' + collect.Path(__file__).split[0]
Logger.setLevel('INFO')


def call(cmd, *args, **Popen_kwargs):
    """Call the given command and exit if the command returned a nonzero exit
    code."""
    if not args:
        cmd, *args = shlex.split(cmd)

    proc = subprocess.Popen([cmd, *args], **Popen_kwargs)
    ret_code = proc.wait()

    if ret_code:
        sys.exit(ret_code)
    else:
        return proc


def wal_palatte():
    """Load the palatte generated by wal in hex and RGB form."""
    with (CACHE_DIR / 'colors.json').open() as file:
        hex_p = json.load(file)['colors']

    rgb_p = {name: tint.hex_to_rgb(color)
             for name, color in hex_p.items()}
    return tuple(hex_p.values()), tuple(rgb_p.values())


def ntp_background():
    """Generate the blurred background image."""
    with (CACHE_DIR / 'wal').open() as file:
        wal_img = file.read()

    out = THEME_DIR / 'img/theme_ntp_background.jpg'
    call(f'convert {wal_img} -scale "1366x768^" -blur "0x10" {out}')


def toolbar(hex_p):
    """Generate the toolbar image based on color0."""
    tint.ImagePath(CONFIG_DIR / 'theme_toolbar.png').tint(
        hex_p[0], THEME_DIR / 'img/theme_toolbar.png')


def frame(hex_p):
    """Generate the frame image based on color1."""
    tint.ImagePath(CONFIG_DIR / 'theme_frame.png').tint(
        hex_p[1], THEME_DIR / 'img/theme_frame.png')


def manifest(rgb_p):
    """Generate the data structure for the manifest.json theme file."""
    return {
        'manifest_version': 2,
        'name': 'wal_chrome',
        'version': '1.0',
        'theme': {
            'images': {
                'theme_ntp_background': 'img/theme_ntp_background.jpg',
                'theme_toolbar': 'img/theme_toolbar.png',
                'theme_frame': 'img/theme_frame.png',
            },
            'colors': {
                'tab_text': rgb_p[7],
                'tab_background_text': rgb_p[8],
                'bookmark_text': rgb_p[7],
                'ntp_background': rgb_p[0],
                'ntp_text': rgb_p[7],
            },
            'properties': {
                'ntp_background_repeat': 'no-repeat',
                'ntp_background_alignment': 'middle middle',
                'ntp_logo_alternate': 0,
            }, }, }


def main():
    hex_p, rgb_p = wal_palatte()
    ntp_background()
    toolbar(hex_p)
    frame(hex_p)

    with (THEME_DIR / 'manifest.json').open('w') as file:
        json.dump(manifest(rgb_p), file)

    Logger.info('Made chrome theme')


if __name__ == '__main__':
    main()
