class AVIcon {

    constructor(params) {
        //for easy recycling when making new icons
        this.params = params;

        //mob context
        this.context = params.mobilizingContext;
        //access to the calling script
        this.scriptContext = params.scriptContext;
        this.audioRenderer = params.audioRenderer;
        //where to put it
        this.HTMLContainer = params.HTMLContainer;

        this.imgPath = params.imgPath;
        this.soundBuffer = params.soundBuffer.slice(0);

        //img
        this.img = document.createElement("img");
        this.img.draggable = false;
        this.img.src = this.imgPath;

        this.img.addEventListener("load", () => {
            console.log(this.img.width, this.img.height);
        });

        //audio
        this.sound = new Mobilizing.audio.Source({ "renderer": this.audioRenderer });
        this.context.addComponent(this.sound);

        const buffer = new Mobilizing.audio.Buffer({
            "renderer": this.audioRenderer,
            "arrayBuffer": this.soundBuffer,
            "decodedCallback": () => {
                this.sound.setBuffer(buffer);
                this.sound.play();//hack to get the duration right on!
                this.sound.stop();
            }
        });

        //get the inner width/duration ratio
        setTimeout(() => {
            this.timePixelRatio = this.img.width / this.sound.duration;
            //console.log(this.img, this.img.width, this.sound.duration, this.timePixelRatio);
        }, 500);

        this.transform = new Transform(this.img);

        //interactivity
        this.img.addEventListener("click", this.onClickHandler.bind(this));
        //this.img.addEventListener("dblclick", this.onDoubleClickHandler.bind(this));

        this.img.addEventListener("mousedown", this.onMouseDownHandler.bind(this));
        this.img.addEventListener("mouseup", this.onMouseUpHandler.bind(this));

        //where to display it
        this.HTMLContainer.appendChild(this.img);

        this.isUIIcon = true;
        this.isCompositionIcon = false;
    }

    /**
     * Duplicate the icon
     * @param {*} event 
     */
    onClickHandler() {

        if (this.isUIIcon && this.scriptContext.editMode) {
            this.scriptContext.addIcon(this.params);
        }
    }

    onMouseDownHandler(event) {
        if (this.isCompositionIcon && this.scriptContext.editMode) {
            this.draggable = true;
        }
        if (this.isUIIcon && !this.scriptContext.editMode) {
            this.play();
            console.log(this.sound);
        }
    }

    onMouseUpHandler(event) {
        this.draggable = false;
    }

    /* onDoubleClickHandler(event) {
        if (this.isUIIcon) {
            this.play();
            console.log(this.sound);
        }
    } */

    play() {
        this.sound.play();
    }

}
