# -*- python -*-

# This example demonstrates how the currents settings
# can be read and transitioned from.


# This file is dual-licensed under GNU General Public License
# version 3 and GNU Free Documentation License version 1.3.


# Copyright © 2014  Mattias Andrée (maandree@member.fsf.org)
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Copyright © 2014  Mattias Andrée (maandree@member.fsf.org)
# 
# Permission is granted to copy, distribute and/or modify this document
# under the terms of the GNU Free Documentation License, Version 1.3
# or any later version published by the Free Software Foundation;
# with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
# You should have received a copy of the GNU General Public License
# along with this software package.  If not, see <http://www.gnu.org/licenses/>.


uses_adhoc_opts = True
'''
:bool  `True` if the configuration script parses the ad-hoc settings
'''


# Get --temperature from Blueshift ad-hoc settigns
temperature_to = int(parser.opts['--temperature'][0])


# Get current colour curves
(drm_get if ttymode else randr_get)(0)()
r_, g_, b_ = r_curve[:], g_curve[:], b_curve[:]
start_over()


# Calculate divergence
temperature(temperature_to, lambda t : divide_by_maximum(cmf_10deg(t)))
f = lambda xy : abs(xy[0] - xy[1])
divergence = max([max(map(f, zip(x, y))) for x, y in curves(r_, g_, b_)])


# Get the end state colour curves
r, g, b = r_curve[:], g_curve[:], b_curve[:]


# Calculate transition time
fadein_time = divergence * 5
fadein_steps = fadein_time * 10

# Function for setting the colour temperature
def adjust(alpha):
    f = lambda on : on[0] * (1 - alpha) + on[1] * alpha
    ccc = curves((r_, r), (g_, g), (b_, b))
    ccc = [(out, list(map(f, zip(old, new)))) for out, (old, new) in ccc]
    for out, curve in ccc:
        out[:] = curve
    (drm if ttymode else randr)(0)

# Perform transition
if divergence and not panicgate:
    signal.signal(signal.SIGTERM, signal_SIGTERM)
    dtime = fadein_time / fadein_steps
    df = 1 / fadein_steps
    trans = 0
    while running:
        try:
            trans += df
            if trans > 1:
                break
            adjust(trans)
            time.sleep(dtime)
        except KeyboardInterrupt:
            running = False
adjust(1)