import BufferReader from './BufferReader'
import { MviewAsset } from '../MviewFiles';


class Parser {

    constructor() {


    }


    parse( buffer: ArrayBuffer ) {

        let br = new BufferReader(buffer);

        let assets: Map<string, MviewAsset> = new Map(); 


        for( ; br.getIndex() < br.getSize(); )
        {

            let name = br.readZeroTerminatedString();
            let type  = br.readZeroTerminatedString();
            
            let flag = br.readUint32();
            let comprressedSize = br.readUint32();
            let size = br.readUint32();

            let data = br.readBytes(comprressedSize)
            let decompressData ;
            if( flag & 1) {

                decompressData = this.decompress(new Uint8Array(data), size);
                
            }
           
            assets.set(name, {name: name,
                type : type as a,
                flag: flag,
                data: decompressData || data
            })

        }
 
        return assets

    }


    parseSceneInfo( sceneData: MviewAsset ) {

        let data;

        try {

            data = JSON.parse(new BufferReader(sceneData.data).asString())
            
        } catch (error) {
            
            throw(`读取场景信息出错：${error}`)

        }

        return data;

    }


    parseTexture( textureData: MviewAsset ) {


    }


    //解压压缩文件 （sky.dat）
    private decompress  (a: Uint8Array, c: number ) {
        var b = new Uint8Array(c)
          , d = 0
          , e = new Uint32Array(4096)
          , f = new Uint32Array(4096)
          , g = 256
          , h = a.length
          , k = 0
          , n = 1
          , m = 0
          , l = 1;
        b[d++] = a[0];
        for (var p = 1; ; p++) {
            l = p + (p >> 1);
            if (l + 1 >= h)
                break;
            var m = a[l + 1]
              , l = a[l]
              , r = p & 1 ? m << 4 | l >> 4 : (m & 15) << 8 | l;
            if (r < g)
                if (256 > r)
                    m = d,
                    l = 1,
                    b[d++] = r;
                else
                    for (var m = d, l = f[r], r = e[r], s = r + l; r < s; )
                        b[d++] = b[r++];
            else if (r == g) {
                m = d;
                l = n + 1;
                r = k;
                for (s = k + n; r < s; )
                    b[d++] = b[r++];
                b[d++] = b[k]
            } else
                break;
            e[g] = k;
            f[g++] = n + 1;
            k = m;
            n = l;
            g = 4096 <= g ? 256 : g
        }
        return d == c ? b : null
    }

    
}

type a = 'sky.dat'|'image/jpeg'|'image/derp'|'model/mset'|'image/jpeg'|'application/json'
export {

    Parser

}


