package o2mc.io.dimmldependency.viewMapper;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by nickyromeijn on 18/02/16.
 */
public class DatastreamsViewmapper {

    private Activity activity;
    private String activityName;

    public DatastreamsViewmapper(Activity activity) {
        this.activity = activity;
        activityName = activity.getClass().getSimpleName();
        initMapping();
    }

    private void initMapping() {
        final HashMap<String, ArrayList<JSONObject>> mappedList = new HashMap<>();
        final ArrayList<View> viewList = getViews();
        viewList.remove(viewList.size() - 1);
        final View trackedView = viewList.get(viewList.size() - 1);
        trackedView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int counter = 0;
                for (View view : viewList) {
                    JSONObject root = new JSONObject();
                    JSONObject child = new JSONObject();
                    Rect rectf = new Rect();
                    view.getGlobalVisibleRect(rectf);

                    try {

                        child.put("width", rectf.width() / 3);
                        child.put("height", rectf.height() / 3);
                        child.put("left", rectf.left / 3);
                        child.put("top", rectf.top / 3);

                        try {
                            root.put("id", activity.getResources().getResourceEntryName(view.getId()));
                        } catch(Exception e){
                            e.printStackTrace();
                        }

                        root.put("indexWithinActivity", counter);

                        if(view.getTag() != null) {
                            root.put("tag", view.getTag().toString());
                        }

                        root.put("type", view.getClass().getSimpleName());
                        root.put("location", child);

                        if(mappedList.get(activityName) == null){
                            mappedList.put(activityName, new ArrayList<JSONObject>());
                        }

                        mappedList.get(activityName).add(root);

                        counter++;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                new DatastreamsViewmapperPost(activity).execute(new DataStore(new JSONObject(mappedList), encodeTobase64(takeScreenshot())));
                trackedView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
//                Log.e("MAP", new JSONObject(mappedList).toString());
//                Log.e("BASE", encodeTobase64(takeScreenshot()));
            }
        });

    }


    public ArrayList<View> getViews() {
        ArrayList<View> views = new ArrayList<View>();
        ViewGroup viewGroup = (ViewGroup) activity.getWindow().getDecorView();
        findViews(viewGroup, views);
        return views;
    }

    public static void findViews(ViewGroup viewGroup, ArrayList<View> views) {
        for (int i = 0, N = viewGroup.getChildCount(); i < N; i++) {
            View child = viewGroup.getChildAt(i);
            if (child instanceof ViewGroup) {
                findViews((ViewGroup) child, views);
            } else if (!(child instanceof ViewStub)) {
                views.add(child);
            }
        }
    }

    private String encodeTobase64(Bitmap immagex)
    {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
        activity.getWindow().getDecorView().setDrawingCacheEnabled(false);

        return "data:image/jpeg;base64,"+imageEncoded;
    }

    private Bitmap takeScreenshot() {
        activity.getWindow().getDecorView().setDrawingCacheEnabled(true);
        return activity.getWindow().getDecorView().getDrawingCache();
    }

}



