package com.hikapro.backpack.model;

import android.graphics.Bitmap;
import android.os.Message;
import android.widget.Toast;

import com.hikapro.backpack.App;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.dao.Command;
import com.hikapro.backpack.model.dao.DAO;
import com.hikapro.backpack.model.dao.Event;
import com.hikapro.backpack.model.entities.Category;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.Presenter;

import java.util.Collections;
import java.util.Hashtable;
import java.util.List;

/**
 * Created by tariel on 16/05/16.
 */
public class ShareModel implements Model.Share {

    private Presenter.Share   presenter;
    private DAO dao;
    private Bitmap[] picCache;

    public ShareModel() {
        this.dao   = DAO.getInstance();

    }

    @Override
    public void onDestroy(boolean isConfigurationChanging) {
        if ( !isConfigurationChanging ) {
            presenter = null;
        }
        dao.unregisterObserver(this);
    }

    @Override
    public void executeQuery() {
        if (picCache == null) {
            Message command;
            dao.registerObserver(this);
            command = Message.obtain();
            command.what = Command.SHARING_GET_PIC;
            dao.executeCommand(command);
        } else
            notifyDataSetChanged();
    }

    @Override
    public void notifyDataSetChanged() {
        if (presenter != null)
            presenter.notifyDataSetChanged();
    }

    @Override
    public void onEvent(Message event) {

        switch (event.what) {
            case Event.SHARING_GET_PIC_ERROR:
                if (!NetworkUtil.isInternetAvailable()) {
                    Toast.makeText(App.getAppContext(), R.string.no_connection, Toast.LENGTH_SHORT).show();
                }
                notifyDataSetChanged();
                break;

            case Event.SHARING_PIC_LOADED:
                picCache = (Bitmap[]) event.obj;
                notifyDataSetChanged();
                break;
        }

    }

    @Override
    public void setPresenter(Presenter.Share presenter) {
        this.presenter = presenter;
    }

    @Override
    public Presenter.Share getPresenter() {
        return presenter;
    }

    public Bitmap[] getSharingPics() {
        return picCache;
    }
}
