package cloud.hmml.mmw;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.decode.ImageDecoder;
import com.nostra13.universalimageloader.core.decode.ImageDecodingInfo;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.IOException;
import java.io.InputStream;


public class MainApplication extends Application {
    class MmwImageDownloader extends BaseImageDownloader {
        public MmwImageDownloader(Context context) {
            super(context);
        }

        @Override
        public InputStream getStream(String imageUri, Object extra) throws IOException {
            if (Uri.parse(imageUri).getScheme().equals("mikuweather-icon"))
                return getStreamFromMikuWeather(imageUri, extra);
            return super.getStream(imageUri, extra);
        }

        public InputStream getStreamFromMikuWeather(String imageUri, Object extra) throws IOException {
            Context mx_context = null;
            Uri uri = Uri.parse(imageUri);
            try {
                mx_context = context.createPackageContext("com.mikuxperia.mikuweatherwidget", Context.CONTEXT_RESTRICTED);
            } catch (PackageManager.NameNotFoundException e) {
                throw new IOException("Faeild to resolv miku weather package");
            }
            Resources resources = mx_context.getResources();
            int resourceId = resources.getIdentifier(uri.getSchemeSpecificPart(), "drawable", "com.mikuxperia.mikuweatherwidget");
            return resources.openRawResource(resourceId);
        }

    }


    @Override
    public void onCreate() {
        super.onCreate();
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
           .cacheInMemory(true)
           .build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .imageDownloader(new MmwImageDownloader(getApplicationContext()))
                .defaultDisplayImageOptions(defaultOptions)
                .build();
        ImageLoader.getInstance().init(config);

    }
}