var Path = require('fire-path');
var Fs = require('fire-fs');

// creat thumbnail
var _createThumbnail = function ( lwipImage, uuid, extname, size, cb ) {
    // start create
    lwipImage.contain( size, size, {r: 255, g: 255, b: 255, a: 0} , 'grid', function (err, image) {
        // check error
        if ( err ) {
            if ( cb ) cb (err);
            return;
        }

        var dest = Editor.AssetDB.mkdirForUuid ( uuid );
        if ( dest ) {
            var thumbFile = Path.join( dest, uuid + '.thumb' + extname );
            image.writeFile(thumbFile, function(err) {
                if ( cb ) cb (err);
            });
        }
    });
};

// enum Type
Fire.TextureType = Fire.defineEnum({
    Texture: -1,
    Sprite: -1,
    NormalMap: -1,
});

Editor.TextureMeta = Fire.Class({
    name: 'Editor.TextureMeta',
    extends: Editor.AssetMeta,

    constructor: function () {
        // overridable function
        this.export = null;
    },

    statics: {
        assetType: Fire.Texture,
    },

    properties: {
        type: {
            default: Fire.TextureType.Sprite,
            type: Fire.TextureType,
        },
        wrapMode: {
            default: Fire.Texture.WrapMode.Clamp,
            type: Fire.Texture.WrapMode,
        },
        filterMode: {
            default: Fire.Texture.FilterMode.Bilinear,
            type: Fire.Texture.FilterMode,
        },
    },

    createAsset: function ( path, cb ) {
        var Lwip = require('lwip');
        Lwip.open( path, function(err, image) {
            if ( err ) {
                cb ( err );
                return;
            }


            var asset = new Fire.Texture();

            asset.width = image.width();
            asset.height = image.height();
            asset._setRawExtname(Path.extname(path));
            asset.lwipImage = image;

            cb ( null, asset );
        });
    },

    import: function ( file ) {
        var meta = file.meta;
        var texture = file.asset;
        var extname = Path.extname(file.path);
        var basename = Path.basename(file.path,extname);

        texture.wrapMode = meta.wrapMode;
        texture.filterMode = meta.filterMode;

        if ( meta.type === Fire.TextureType.Sprite ) {
            var needSprite = false;

            if ( !meta.subRawData || meta.subRawData.length === 0 ) {
                meta.subRawData = [];
                needSprite = true;
            }

            // if we don't have sub-assets, create one
            if ( needSprite ) {
                var Uuid = require('node-uuid');

                var sprite = new Fire.Sprite();
                sprite.name = basename;
                sprite.texture = Editor.serialize.asAsset(meta.uuid);
                sprite.width = texture.width;
                sprite.height = texture.height;
                sprite.rawWidth = texture.width;
                sprite.rawHeight = texture.height;

                var spriteMeta = new Editor.SpriteMeta();
                spriteMeta.uuid = Uuid.v4();
                spriteMeta.rawTextureUuid = meta.uuid;

                meta.subRawData.push({ asset: sprite, meta: spriteMeta });
            }
        }
        else {
            // clear unused sub asset if we do not change the type
            if ( meta.subRawData && meta.subRawData.length > 0 ) {
                meta.subRawData = [];
            }
        }

        //
        var scope = this;
        var rawExtname = '.' + texture._rawext;
        var Async = require('async');
        Async.series([
            function ( cb ) {
                Editor.AssetDB.saveAssetToLibrary( meta.uuid, texture, cb );
            },
            function ( cb ) {
                // if rawfile exists
                if ( Fs.existsSync( file.path ) ) {
                    Editor.AssetDB.copyToLibrary( file.meta.uuid, rawExtname, file.path, cb );
                }
                // else if the texture is created in memory
                else {
                    var libpath = Editor.AssetDB.uuidToLibraryPath(meta.uuid);
                    texture.lwipImage.writeFile( libpath + rawExtname, cb );
                }
            },
            function ( cb ) {
                _createThumbnail( texture.lwipImage, meta.uuid, rawExtname, 32, cb );
            },
        ], function ( err, results ) {
            if ( err ) {
                scope.error(err);
                return;
            }
            scope.done();
        });
    },
});
