/*
    Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
    Copyright (C) 2001 Dirk Mueller <mueller@kde.org>
    Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
    Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#pragma once

#include "CachedImageClient.h"
#include "CachedResource.h"
#include "ImageObserver.h"
#include "IntRect.h"
#include "IntSizeHash.h"
#include "LayoutSize.h"
#include "SVGImageCache.h"
#include <wtf/HashMap.h>
#include <wtf/HashSet.h>
#include <wtf/Vector.h>
#include <wtf/WeakHashSet.h>

namespace WebCore {

class CachedImageClient;
class CachedResourceLoader;
class FloatSize;
class MemoryCache;
class RenderElement;
class RenderObject;
class SecurityOrigin;

struct Length;

class CachedImage FINAL : public CachedResource {
    friend class MemoryCache;

public:
    explicit CachedImage(CachedResourceRequest&);

    static CachedImage* create(Image*);

    virtual ~CachedImage();
    
    virtual ResourceError load(CachedResourceLoader*) OVERRIDE;

    Image* image() const; // Returns the nullImage() if the image is not available yet.
    Image* imageForRenderer(const RenderObject*); // Returns the nullImage() if the image is not available yet.
    bool hasImage() const { return m_image.get(); }
    bool hasSVGImage() const;
    bool currentFrameKnownToBeOpaque(const RenderElement*); // Side effect: ensures decoded image is in cache, therefore should only be called when about to draw the image.

    std::pair<Image*, float> brokenImage(float deviceScaleFactor) const; // Returns an image and the image's resolution scale factor.
    bool willPaintBrokenImage() const; 

    bool canRender(const RenderElement* renderer, float multiplier) { return !errorOccurred() && !imageSizeForRenderer(renderer, multiplier).isEmpty(); }

    void setContainerContextForClient(const CachedImageClient&, const LayoutSize&, float, const KURL&);
	bool usesImageContainerSize() const;
    bool imageHasRelativeWidth() const;
    bool imageHasRelativeHeight() const;

    enum SizeType {
        UsedSize,
        IntrinsicSize
    };
    WEBCORE_EXPORT FloatSize imageSizeForRenderer(const RenderElement* renderer, SizeType = UsedSize) const;
	// This method takes a zoom multiplier that can be used to increase the natural size of the image by the zoom.
    LayoutSize imageSizeForRenderer(const RenderElement*, float multiplier, SizeType = UsedSize) const; // returns the size of the complete image.
    LayoutSize unclampedImageSizeForRenderer(const RenderElement* renderer, float multiplier, SizeType = UsedSize) const;
	void computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio);

    bool isManuallyCached() const { return m_isManuallyCached; }
    virtual RevalidationDecision makeRevalidationDecision(CachePolicy) const OVERRIDE;

    virtual void didAddClient(CachedResourceClient&) OVERRIDE;
    virtual void didRemoveClient(CachedResourceClient&) OVERRIDE;

    virtual void allClientsRemoved() OVERRIDE;
    virtual void handleOutOfMemory(bool clearRawData) OVERRIDE;
    virtual void destroyDecodedData() OVERRIDE;

    virtual void addDataBuffer(SharedBuffer*) OVERRIDE;
    virtual void finishLoading(SharedBuffer*) OVERRIDE;

    virtual void addData(const char* data, unsigned length) OVERRIDE;
    virtual void error(CachedResource::Status) OVERRIDE;
    virtual void responseReceived(const ResourceResponse&) OVERRIDE;
    
    // For compatibility, images keep loading even if there are HTTP errors.
    virtual bool shouldIgnoreHTTPStatusCodeErrors() const OVERRIDE { return true; }

    virtual bool stillNeedsLoad() const OVERRIDE { return !errorOccurred() && status() == Unknown && !isLoading(); }
    bool canSkipRevalidation(const CachedResourceLoader&, const CachedResourceRequest&) const;

    class CachedImageObserver final : public ImageObserver {
    public:
        static PassRefPtr<CachedImageObserver> create(CachedImage& image) { return adoptRef(new CachedImageObserver(image)); }
        WeakHashSet<CachedImage>& cachedImages() { return m_cachedImages; }
		const WeakHashSet<CachedImage>& cachedImages() const { return m_cachedImages; }

    private:
        explicit CachedImageObserver(CachedImage&);

        // ImageObserver API
        virtual KURL sourceUrl() const OVERRIDE { return !m_cachedImages.isEmptyIgnoringNullReferences() ? (*m_cachedImages.begin()).url() : KURL(); }
        String mimeType() const override { return !m_cachedImages.isEmptyIgnoringNullReferences() ? (*m_cachedImages.begin()).mimeType() : emptyString(); }
		long long expectedContentLength() const override { return !m_cachedImages.isEmptyIgnoringNullReferences() ? (*m_cachedImages.begin()).expectedContentLength() : 0; }

		virtual void decodedSizeChanged(const Image* image, int delta) OVERRIDE;
		virtual void didDraw(const Image*) OVERRIDE;

		virtual void animationAdvanced(const Image*) OVERRIDE;
	    bool canDestroyDecodedData(const Image*) override { return true; }
		virtual void changedInRect(const Image*, const IntRect&) OVERRIDE;
        virtual void scheduleRenderingUpdate(const Image&) FINAL;

        WeakHashSet<CachedImage> m_cachedImages;
    };

    void decodedSizeChanged(const Image* image, int delta);
    void didDraw(const Image*);

    void animationAdvanced(const Image*);
    void changedInRect(const Image*, const IntRect&);
    void scheduleRenderingUpdate(const Image&);

    void acceleratedSurfaceDeletionTimerCallback();

    bool isOriginClean(SecurityOrigin*);

private:
    void clear();

    CachedImage(CachedImage&, const ResourceRequest&);
    CachedImage(Image*);

    virtual void setBodyDataFrom(const CachedResource&) FINAL;

    bool isPDFResource() const;
    bool isPostScriptResource() const;

    void createImage();
    void clearImage();
    bool canBeDrawn() const;
    // If not null, changeRect is the changed part of the image.
    void notifyObservers(const IntRect* changeRect, bool allDataReceived);
    void checkShouldPaintBrokenImage();

    virtual void switchClientsToRevalidatedResource() OVERRIDE;
    virtual bool mayTryReplaceEncodedData() const OVERRIDE { return true; }

    void addIncrementalDataBuffer(SharedBuffer*);

    struct ContainerContext {
    	ContainerContext() : containerZoom(1.0) { }
    	ContainerContext(const LayoutSize& containerSize, float containerZoom, const KURL& imageURL)
    		: containerSize(containerSize)
    		, containerZoom(containerZoom)
    		, imageURL(imageURL)
    	{
    	}
        LayoutSize containerSize;
        float containerZoom;
        KURL imageURL;
    };

    typedef HashMap<const CachedImageClient*, ContainerContext> ContainerContextRequests;
    ContainerContextRequests m_pendingContainerContextRequests;

    WeakHashSet<CachedImageClient> m_clientsWaitingForAsyncDecoding;

    RefPtr<CachedImageObserver> m_imageObserver;
    RefPtr<Image> m_image;
#if ENABLE(SVG)
    OwnPtr<SVGImageCache> m_svgImageCache;
#endif

    WeakPtr<Document> m_skippingRevalidationDocument;

    bool m_isManuallyCached;
    bool m_shouldPaintBrokenImage;

	Timer<CachedImage> m_acceleratedSurfaceDeletionTimer;
};

inline bool isCachedImage(const CachedResource& resource)
{
	return resource.type() == CachedResource::Type::ImageResource;
}

}

// SPECIALIZE_TYPE_TRAITS_CACHED_RESOURCE(CachedImage, CachedResource::Type::ImageResource)
