package com.rthoni.camotion.business;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import com.luticate.utils.business.LuBusinessManager;
import com.luticate.utils.business.LuPromise;
import com.luticate.utils.dbo.LuDataAccessConfigDbo;
import com.rthoni.camotion.dataaccess.CamerasDataAccess;
import com.rthoni.camotion.dbo.CameraDbo;
import com.rthoni.camotion.dbo.CameraImageDbo;

/**
 * Created by robin on 12/3/15.
 */
public class CamerasBusiness extends LuBusinessManager {
    public static LuPromise<CameraDbo.MultipleCameraDbo> getAll(LuDataAccessConfigDbo config, int page, int perPage)
    {
        return CamerasDataAccess.getAll(config, page, perPage);
    }

    public static LuPromise<Bitmap> getImage(LuDataAccessConfigDbo config, CameraDbo camera)
    {
        final LuPromise<Bitmap> promise = new LuPromise<>();

        CamerasDataAccess.getImage(config, camera.getId()).then(new LuPromise.LuConsumer<CameraImageDbo>() {
            @Override
            public void execute(CameraImageDbo image) {
                try
                {
                    byte[] data = Base64.decode(image.getImage(), Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    promise.resolve(bitmap);
                } catch (Exception e)
                {
                    promise.reject(new LuPromise.LuPromiseError(e.getMessage(), 200));
                }
            }
        }, promise.rejectConsumer());

        return promise;
    }
}
