import { VideoEntity } from './videoEntity'
import MockWorker from './mockWorker'

export class Parser {

    /**
     * url: 资源路径
     * success(VideoEntity videoItem)
     */
    load(url, success, failure) {
        this.loadViaWorker(url, success, failure);
    }

    loadViaWorker(url, success, failure) {
        MockWorker(url, (data) => {
            let movie = data.movie;
            movie["version"] = data.ver;
            let images = data.images;

            // let videoItem = new VideoEntity(movie, images);
            // success(videoItem);
            //白鹭的在base64图片都加载完用标签传
            let countAll = Object.getOwnPropertyNames(images).length;
            let count = 0;
            let htmlImages = {};
            for (let key in images) {
                var bitmap = images[key];
                let imgTag = new Image();
                let backCanvas;
                if (bitmap.indexOf("iVBO") === 0 || bitmap.indexOf("/9j/2w") === 0) {
                    imgTag.src = 'data:image/png;base64,' + bitmap;
                }
                else {
                    // imgTag.src = bitmap;
                    // if (frames[0] && frames[0].layout) {
                    //     backCanvas = document.createElement('canvas');
                    //     backCanvas.width = frames[0].layout.width
                    //     backCanvas.height = frames[0].layout.height
                    //     imgTag.onload = function () {
                    //         backCanvas.getContext('2d').drawImage(imgTag, 0, 0, frames[0].layout.width, frames[0].layout.height)
                    //     }
                    // }
                }
                //必须加载完成才行
                imgTag.onload = function () {
                    count++;
                    htmlImages[key] = backCanvas || imgTag;
                    if (count == countAll) {
                        let videoItem = new VideoEntity(movie, htmlImages);
                        success(videoItem);
                    }
                }
            }
        }, failure)
    }

}