import { knownFolders, path as filePath, Observable } from '@nativescript/core';
import { Helpers } from '../helpers';
let ctor;
// store ref if loading
const loaders = new Map();
export class ImageAsset extends Observable {
    get native() {
        return this._native;
    }
    constructor(native) {
        super();
        this._native = native || new global.CanvasModule.ImageAsset();
        if (__ANDROID__) {
            const ref = long(this.native.__getRef());
            this._android = new org.nativescript.canvas.NSCImageAsset(ref);
        }
    }
    get width() {
        return this.native.width;
    }
    get height() {
        return this.native.height;
    }
    get error() {
        return this.native.error;
    }
    fromUrlSync(url) {
        return this.native.fromUrlSync(url);
    }
    _incrementStrongRef() {
        let count = 0;
        if (loaders.has(this)) {
            count = loaders.get(this);
        }
        count++;
        loaders.set(this, count);
    }
    _decrementStrongRefAndRemove() {
        const count = loaders.get(this) - 1;
        if (count <= 0) {
            loaders.delete(this);
        }
    }
    emitComplete(success, error) {
        this.notify({ eventName: 'complete', object: this, complete: success, error });
    }
    fromUrl(url) {
        return new Promise((resolve, reject) => {
            if (__ANDROID__) {
                const asset = this._android.getAsset();
                const ref = new WeakRef(this);
                org.nativescript.canvas.NSCImageAsset.loadImageFromUrlAsync(asset, url, new org.nativescript.canvas.NSCImageAsset.Callback({
                    onComplete(success) {
                        const owner = ref.get();
                        if (!success) {
                            const error = org.nativescript.canvas.NSCImageAsset.getError(asset);
                            if (owner) {
                                owner.emitComplete(success, error);
                            }
                            reject(error);
                        }
                        else {
                            if (owner) {
                                owner.emitComplete(success, undefined);
                            }
                            resolve(success);
                        }
                    },
                }));
                return;
            }
            this._incrementStrongRef();
            this.native.fromUrlCb(url, (success, error) => {
                this.emitComplete(success, error);
                if (error) {
                    reject(error);
                }
                else {
                    resolve(success);
                }
                this._decrementStrongRefAndRemove();
            });
        });
    }
    fromFileSync(path) {
        let realPath = path;
        if (typeof realPath === 'string') {
            if (realPath.startsWith('~/')) {
                realPath = filePath.join(knownFolders.currentApp().path, realPath.replace('~/', ''));
            }
        }
        const ret = this.native.fromFileSync(realPath);
        return ret;
    }
    fromFile(path) {
        return new Promise((resolve, reject) => {
            if (typeof path === 'string') {
                if (path.startsWith('~/')) {
                    path = filePath.join(knownFolders.currentApp().path, path.replace('~/', ''));
                }
            }
            if (__ANDROID__) {
                const asset = this._android.getAsset();
                const ref = new WeakRef(this);
                if (typeof path === 'string' && path.indexOf('.webp') > -1) {
                    org.nativescript.canvas.NSCImageAsset.loadWebPAsync(asset, path, new org.nativescript.canvas.NSCImageAsset.Callback({
                        onComplete(success) {
                            const owner = ref.get();
                            if (!success) {
                                const error = org.nativescript.canvas.NSCImageAsset.getError(asset);
                                if (owner) {
                                    owner.emitComplete(success, error);
                                }
                                reject(error);
                            }
                            else {
                                if (owner) {
                                    owner.emitComplete(success, undefined);
                                }
                                resolve(success);
                            }
                        },
                    }));
                }
                else {
                    org.nativescript.canvas.NSCImageAsset.loadImageFromPathAsync(asset, path, new org.nativescript.canvas.NSCImageAsset.Callback({
                        onComplete(success) {
                            const owner = ref.get();
                            if (!success) {
                                const error = org.nativescript.canvas.NSCImageAsset.getError(asset);
                                if (owner) {
                                    owner.emitComplete(success, error);
                                }
                                reject(error);
                            }
                            else {
                                if (owner) {
                                    owner.emitComplete(success, undefined);
                                }
                                resolve(success);
                            }
                        },
                    }));
                }
                return;
            }
            this._incrementStrongRef();
            this.native.fromFileCb(path.toString(), (success, error) => {
                this.emitComplete(success, error);
                if (error) {
                    reject(error);
                }
                else {
                    resolve(success);
                }
                this._decrementStrongRefAndRemove();
            });
        });
    }
    /*

    loadFromNative(image: any): boolean {
        return this.native.loadImageFromImage(image);
    }

    loadFromNative(image: any) {
        return new Promise((resolve, reject) => {
            this.native.loadImageFromImage(
                image,
                new org.nativescript.canvas.TNSImageAsset.Callback({
                    onError(error) {
                        reject(error);
                    },
                    onSuccess(success) {
                        resolve(success);
                    },
                })
            );
        });
    }

    */
    loadFromBytesSync(bytes) {
        return this.native.fromBytesSync(bytes);
    }
    loadFromBytes(bytes) {
        return new Promise((resolve, reject) => {
            if (__ANDROID__) {
                const ref = new WeakRef(this);
                const asset = this._android.getAsset();
                if (!ArrayBuffer.isView(bytes)) {
                    org.nativescript.canvas.NSCImageAsset.loadImageFromBytesAsync(asset, bytes, new org.nativescript.canvas.NSCImageAsset.Callback({
                        onComplete(success) {
                            const owner = ref.get();
                            if (!success) {
                                const error = org.nativescript.canvas.NSCImageAsset.getError(asset);
                                if (owner) {
                                    owner.emitComplete(success, error);
                                }
                                reject(error);
                            }
                            else {
                                if (owner) {
                                    owner.emitComplete(success, undefined);
                                }
                                resolve(success);
                            }
                        },
                    }));
                }
                else {
                    org.nativescript.canvas.NSCImageAsset.loadImageFromBufferAsync(asset, bytes, new org.nativescript.canvas.NSCImageAsset.Callback({
                        onComplete(success) {
                            const owner = ref.get();
                            if (!success) {
                                const error = org.nativescript.canvas.NSCImageAsset.getError(asset);
                                if (owner) {
                                    owner.emitComplete(success, error);
                                }
                                reject(error);
                            }
                            else {
                                if (owner) {
                                    owner.emitComplete(success, undefined);
                                }
                                resolve(success);
                            }
                        },
                    }));
                }
                return;
            }
            this._incrementStrongRef();
            this.native.fromBytesCb(bytes, (success, error) => {
                this.emitComplete(success, error);
                if (error) {
                    reject(error);
                }
                else {
                    resolve(success);
                }
                this._decrementStrongRefAndRemove();
            });
        });
    }
    scale(x, y) {
        this.native.scale(x, y);
    }
    saveSync(path, format) {
        return this.native.saveSync(path, format);
    }
    save(path, format) {
        return new Promise((resolve, reject) => {
            this._incrementStrongRef();
            this.native.saveCb(path, format, (success, error) => {
                if (error) {
                    reject(error);
                }
                else {
                    resolve(success);
                }
                this._decrementStrongRefAndRemove();
            });
        });
    }
    flipX() { }
    flipY() { }
}
(() => {
    Helpers.initialize();
})();
export var ImageAssetSaveFormat;
(function (ImageAssetSaveFormat) {
    ImageAssetSaveFormat[ImageAssetSaveFormat["JPG"] = 0] = "JPG";
    ImageAssetSaveFormat[ImageAssetSaveFormat["PNG"] = 1] = "PNG";
    ImageAssetSaveFormat[ImageAssetSaveFormat["ICO"] = 2] = "ICO";
    ImageAssetSaveFormat[ImageAssetSaveFormat["BMP"] = 3] = "BMP";
    ImageAssetSaveFormat[ImageAssetSaveFormat["TIFF"] = 4] = "TIFF";
})(ImageAssetSaveFormat || (ImageAssetSaveFormat = {}));
//# sourceMappingURL=index.js.map