/*
 * Copyright (C) 2017 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#pragma once

#include "AnimationEffect.h"
#include "AnimationEffectPhase.h"
#include "CSSPropertyBlendingClient.h"
#include "CompositeOperation.h"
#include "CompositeOperationOrAuto.h"
#include "EffectTiming.h"
#include "CompositeOperation.h"
#include "Element.h"
#include "ExceptionCode.h"
#include "IterationCompositeOperation.h"
#include "JSCompositeOperationOrAuto.h"
#include "KeyframeEffectOptions.h"
#include "KeyframeList.h"
#include "RenderStyle.h"
#include "ScriptValue.h"
#include "StylePropertySet.h"
#include "Styleable.h"
#include "WebAnimationTypes.h"
#include <wtf/PassRefPtr.h>

namespace WebCore {

class Element;
class FilterOperations;

namespace Style {
struct ResolutionContext;
}

class KeyframeEffect : public AnimationEffect
    , public CSSPropertyBlendingClient {
public:
	struct BaseKeyframe {
	    Optional<double> offset;
	    String easing { "linear" };
	    CompositeOperationOrAuto composite { CompositeOperationOrAuto::Auto };
	};

	struct BaseComputedKeyframe {
	    Optional<double> offset;
	    double computedOffset { 0 };
	    String easing { "linear" };
	    CompositeOperationOrAuto composite { CompositeOperationOrAuto::Auto };
	};

    static PassRefPtr<KeyframeEffect> create(JSC::ExecState&, Element*, JSC::JSValue keyframes, JSC::JSValue options, ExceptionCode&);
    static PassRefPtr<KeyframeEffect> create(JSC::ExecState&, KeyframeEffect&, ExceptionCode&);
    static PassRefPtr<KeyframeEffect> create(const Element&, PseudoId);
	virtual ~KeyframeEffect() { }

    struct BasePropertyIndexedKeyframe {
    	Vector<Optional<double>> offset; // Variant<std::nullptr_t, Vector<std::optional<double>>, double> offset = Vector<std::optional<double>>();
    	Vector<String> easing; // Variant<Vector<String>, String> easing = Vector<String>();
    	Vector<CompositeOperationOrAuto> composite; // Variant<Vector<CompositeOperationOrAuto>, CompositeOperationOrAuto> composite = Vector<CompositeOperationOrAuto>();
    };

    struct PropertyAndValues {
        CSSPropertyID property;
        Vector<String> values;
    };

    struct KeyframeLikeObject {
        BasePropertyIndexedKeyframe baseProperties;
        Vector<PropertyAndValues> propertiesAndValues;
    };

    struct ParsedKeyframe {
        Optional<double> offset;
        double computedOffset;
        CompositeOperationOrAuto composite;
        String easing;
        RefPtr<TimingFunction> timingFunction;
        Ref<MutableStylePropertySet> style;
        HashMap<CSSPropertyID, String> styleStrings;

        ParsedKeyframe()
            : computedOffset(0)
        	, composite(CompositeOperationOrAuto::Auto)
        	, style(MutableStylePropertySet::create())
        {
        }
    };

    Element* target() const { return m_target.get(); }
    Element* targetElementOrPseudoElement() const;
    void setTarget(PassRefPtr<Element>);

    bool targetsPseudoElement() const;
    const String pseudoElement() const;
    void setPseudoElement(const String&, ExceptionCode&);

    Optional<Styleable> targetStyleable() const;

    JSC::JSValue getBindingsKeyframes(JSC::ExecState*); // Vector<JSC::Strong<JSC::JSObject>>
    JSC::JSValue getKeyframes(JSC::ExecState*); // Vector<JSC::Strong<JSC::JSObject>>
    void setBindingsKeyframes(JSC::ExecState*, JSC::JSValue, ExceptionCode&);
    void setKeyframes(JSC::ExecState*, JSC::JSValue, ExceptionCode&);

    IterationCompositeOperation iterationComposite() const { return m_iterationCompositeOperation; }
    void setIterationComposite(IterationCompositeOperation iterationCompositeOperation);
    CompositeOperation composite() const { return m_compositeOperation; }
    void setComposite(CompositeOperation);

    void getAnimatedStyle(OwnPtr<RenderStyle>& animatedStyle);
    void apply(RenderStyle& targetStyle, const Style::ResolutionContext&, Optional<Seconds> = Nullopt);
	void invalidate();
    void animationTimingDidChange();
    void transformRelatedPropertyDidChange();

    void willChangeRenderer();

    virtual RenderElement* renderer() const OVERRIDE;
    virtual const RenderStyle& currentStyle() const OVERRIDE;
    bool triggersStackingContext() const { return m_triggersStackingContext; }

#if USE(ACCELERATED_COMPOSITING) && !PLATFORM(ESPIAL)
    void applyPendingAcceleratedActions();
    bool isRunningAccelerated() const { return m_lastRecordedAcceleratedAction != AcceleratedAction::Stop; }
    // FIXME: These ignore the fact that some timing functions can prevent acceleration.
    bool isAboutToRunAccelerated() const { return m_acceleratedPropertiesState != AcceleratedProperties::None && m_lastRecordedAcceleratedAction != AcceleratedAction::Stop; }
    bool isRunningAcceleratedTransformRelatedAnimation() const;
    bool hasPendingAcceleratedAction() const { return !m_pendingAcceleratedActions.isEmpty() && isRunningAccelerated(); }
#else
    bool isRunningAccelerated() const { return false; }
    bool canBeAccelerated() const { return false; }
    bool isCompletelyAccelerated() const { return false; }
    bool isAboutToRunAccelerated() const { return false; }
    bool isRunningAcceleratedTransformRelatedAnimation() const { return false; }
    bool hasPendingAcceleratedAction() const { return false; }
#endif

    // The CoreAnimation animation code can only use direct function interpolation when all keyframes share the same
    // prefix of shared transform function primitives, whereas software animations simply calls blend(...) which can do
    // direct interpolation based on the function list of any two particular keyframes. The prefix serves as a way to
    // make sure that the results of blend(...) can be made to return the same results as rendered by the hardware
    // animation code.
    Optional<unsigned> transformFunctionListPrefix() const override { return (!preventsAcceleration()) ? Optional<unsigned>(m_transformFunctionListsMatchPrefix) : Nullopt; }

    void computeDeclarativeAnimationBlendingKeyframes(const RenderStyle* oldStyle, const RenderStyle& newStyle, const Style::ResolutionContext&);
    bool hasBlendingKeyframes() const { return m_blendingKeyframes.size(); }
    const KeyframeList& blendingKeyframes() const { return m_blendingKeyframes; }
    const HashSet<CSSPropertyID>& animatedProperties();
    bool animatesProperty(CSSPropertyID) const;

    bool forceLayoutIfNeeded();

    enum class Accelerated : uint8_t { Yes, No };
    bool isCurrentlyAffectingProperty(CSSPropertyID, Accelerated = Accelerated::No) const;

    bool requiresPseudoElement() const;
    bool hasImplicitKeyframes() const;

    void keyframesRuleDidChange();

    bool preventsAcceleration() const;

private:
    KeyframeEffect(Element*, PseudoId);

    enum class AcceleratedAction : uint8_t { Play, Pause, UpdateTiming, TransformChange, Stop };
    enum class BlendingKeyframesSource : uint8_t { CSSAnimation, CSSTransition, WebAnimation };
    enum class AcceleratedProperties : uint8_t { None, Some, All };

    Document* document() const;
    void updateEffectStackMembership();
    void copyPropertiesFromSource(KeyframeEffect&);
    void didChangeTargetStyleable(const Optional<Styleable>&);
	void processKeyframes(JSC::ExecState&, JSC::JSValue, ExceptionCode&);
#if USE(ACCELERATED_COMPOSITING) && !PLATFORM(ESPIAL)
    void addPendingAcceleratedAction(AcceleratedAction);
    bool canBeAccelerated() const;
    bool isCompletelyAccelerated() const { return m_acceleratedPropertiesState == AcceleratedProperties::All; }
    void updateAcceleratedActions();
#endif
    void setAnimatedPropertiesInStyle(RenderStyle&, double);
    TimingFunction* timingFunctionForKeyframeAtIndex(size_t) const;
    TimingFunction* timingFunctionForBlendingKeyframe(const KeyframeValue&) const;
    PassRefPtr<Animation> backingAnimationForCompositedRenderer() const;
    void computedNeedsForcedLayout();
    void computeStackingContextImpact();
    void computeSomeKeyframesUseStepsTimingFunction();
    void clearBlendingKeyframes();
    void updateBlendingKeyframes(RenderStyle& elementStyle, const Style::ResolutionContext&);
    void computeCSSAnimationBlendingKeyframes(const RenderStyle& unanimatedStyle, const Style::ResolutionContext&);
	void computeCSSTransitionBlendingKeyframes(const RenderStyle* oldStyle, const RenderStyle& newStyle);
    void computeAcceleratedPropertiesState();
    void setBlendingKeyframes(KeyframeList&&);
    void checkForMatchingTransformFunctionLists();

    // AnimationEffect
    bool isKeyframeEffect() const final { return true; }
    void animationDidTick() final;
    void animationDidPlay() final;
    void animationDidChangeTimingProperties() final;
    void animationWasCanceled() final;
    void animationSuspensionStateDidChange(bool) final;
    void animationTimelineDidChange(AnimationTimeline*) final;
    void setAnimation(WebAnimation*) final;
    Seconds timeToNextTick(BasicEffectTiming) const final;
    bool ticksContinouslyWhileActive() const final;
    Optional<double> progressUntilNextStep(double) const final;

    WeakPtr<Element> m_target;
    PseudoId m_pseudoId;
    KeyframeList m_blendingKeyframes;
    HashSet<CSSPropertyID> m_animatedProperties;
    Vector<ParsedKeyframe> m_parsedKeyframes;
    IterationCompositeOperation m_iterationCompositeOperation;
    CompositeOperation m_compositeOperation;

#if USE(ACCELERATED_COMPOSITING) && !PLATFORM(ESPIAL)
    Vector<AcceleratedAction, 0, CrashOnOverflow, 1> m_pendingAcceleratedActions;
#endif

#if USE(ACCELERATED_COMPOSITING) && !PLATFORM(ESPIAL)
    AcceleratedAction m_lastRecordedAcceleratedAction;
#endif
    BlendingKeyframesSource m_blendingKeyframesSource;
    AcceleratedProperties m_acceleratedPropertiesState { AcceleratedProperties::None };
	AnimationEffectPhase m_phaseAtLastApplication { AnimationEffectPhase::Idle };
	bool m_isRunningAccelerated { false };
    bool m_needsForcedLayout { false };
    bool m_triggersStackingContext { false };
    size_t m_transformFunctionListsMatchPrefix { 0 };
    bool m_inTargetEffectStack { false };
    bool m_someKeyframesUseStepsTimingFunction { false };
};

inline bool isKeyframeEffect(const AnimationEffect* effect)
{
	return effect && effect->isKeyframeEffect();
}

} // namespace WebCore

//SPECIALIZE_TYPE_TRAITS_ANIMATION_EFFECT(KeyframeEffect, isKeyframeEffect());
