package com.vk.vktestapp.actyvity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.vk.sdk.VKUIHelper;
import com.vk.sdk.api.VKParameters;
import com.vk.vktestapp.MainAplication;
import com.vk.vktestapp.R;
import com.vk.vktestapp.utils.ContentLoader;
import com.vk.vktestapp.utils.ImageCache;
import com.vk.vktestapp.utils.ImageLoader;
import com.vk.vktestapp.utils.MyJsonHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PostFeedActivity extends ActionBarActivity implements ContentLoader.OnContentLoaderListener {

    JSONObject item = null;
    JSONObject profile = null;
    Map<String, Object> group = null;
    private ImageCache imageCache;
    private LayoutInflater inflater;
    private Integer date;
    private String type = "post";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        VKUIHelper.onCreate(this);
        setContentView(R.layout.post_feed);
        Bundle extras = getIntent().getExtras();
        imageCache = ((MainAplication) getApplicationContext()).getImageCache();
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        date = extras.getInt("date");
        VKParameters params = new VKParameters();
        params.put("count", 1);
        params.put("end_time", date);
        params.put("start_time", date - 1);

        VKParameters pref = new VKParameters();
        pref.put("group", "newsfeed");
        pref.put("method", "get");


        findViewById(R.id.pf_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        new ContentLoader(this).execute(params, pref);

    }

    private void fillContent(JSONObject response) {

        try {
            item = (JSONObject)response.optJSONArray("items").get(0);
            profile = (JSONObject)response.optJSONArray("profiles").get(0);

            long date = item.getLong("date");

            String firstName = "";
            String lastName = "";
            String photo = null;
            if (profile != null) {
                firstName = profile.getString("first_name");
                lastName = profile.getString("last_name");
                photo = profile.getString("photo_50");
            }
            String likes = null;
            String reps = null;
            String comments = null;
            if (item.optJSONObject("likes") != null)
            likes = item.optJSONObject("likes").optString("count");
            if (item.optJSONObject("reposts") != null)
            reps = item.optJSONObject("reposts").optString("count");
            if (item.optJSONObject("comments") != null)
            comments = item.optJSONObject("comments").optString("count");

            if (!"0".equals(comments)){
                VKParameters params = new VKParameters();

                type = "comments";
                params.put("owner_id", item.getInt("source_id"));
                params.put("post_id", item.getInt("post_id"));
                params.put("need_likes", 1);
                params.put("extended", 1);

                VKParameters pref = new VKParameters();
                pref.put("group", "wall");
                pref.put("method", "getComments");
                new ContentLoader(this).execute(params, pref);
            }

            JSONArray history = item.optJSONArray("copy_history");
            JSONArray attsArray = item.optJSONArray("attachments");
            JSONObject photos = item.optJSONObject("photos");

            String txt = null;
            if (history != null){
                JSONObject historyMap = null;
                    historyMap = (JSONObject) history.get(0);
                txt = historyMap.getString("text");
            fillAtts( historyMap.optJSONArray("attachments"));
            } else if (attsArray != null){
                txt = item.getString("text");
            fillAtts(attsArray);
            } else if (photos != null) {
                txt = photos.optJSONArray("items").getJSONObject(0).optString("text");
                fillAtts(photos.optJSONArray("items"));
            } else {
                    txt = item.getString("text");
            }

            ImageView avatar = (ImageView) findViewById(R.id.pf_avatar);
            Bitmap bm = imageCache.getBitmapFromMemCache(photo);
            if (bm == null || bm.isRecycled()){
                new ImageLoader(this, avatar).execute(photo);
            } else {
                avatar.setImageBitmap(bm);
            }

            ((TextView) findViewById(R.id.pf_name)).setText(firstName + " " + lastName);
            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
            ((TextView) findViewById(R.id.pf_date)).setText(sdf.format(new Date(date * 1000)));
            ((TextView) findViewById(R.id.pf_text)).setText(txt);

            ((TextView) findViewById(R.id.likeCounts)).setText(likes);
            ((TextView) findViewById(R.id.repostCounts)).setText(reps);

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

    private void fillAtts(JSONArray list) {
        if (list == null || list.length() == 0){
            return;
        }
        LinearLayout gv = (LinearLayout) findViewById(R.id.pf_contentContainer);
        for (int i = 0; i < list.length(); i++) {
            ImageView photo = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 5, 5, 5);
            photo.setLayoutParams(params);
            photo.setScaleType(ImageView.ScaleType.CENTER_CROP);
            photo.setAdjustViewBounds(true);

            JSONObject atts = null;
            try {
                atts = (JSONObject) list.opt(i);
                String attsType = atts.optString("type");
                JSONObject photoMap = null;
                String url = null;
                if (attsType.isEmpty()) attsType = "photos";
                switch (attsType) {
                    case "photo":
                        photoMap = atts.getJSONObject("photo");
                        setPrePhot((Integer) photoMap.get("height"), (Integer) photoMap.get("width"), photo);
                        url = photoMap.getString("photo_130");
                        break;
                    case "video":
                        photoMap = atts.getJSONObject("video");
                        setPrePhot(450, 800, photo);
                        url = photoMap.getString("photo_800");
                        break;
                    case "photos":
                        setPrePhot(450, 800, photo);
                        url = atts.getString("photo_807");
                        break;
                }
                Bitmap bm = imageCache.getBitmapFromMemCache(url);
                if ((bm == null  || bm.isRecycled())&& url != null) {
                    new ImageLoader(this, photo).execute(url);
                } else {
                    photo.setImageBitmap(bm);
                }

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

            gv.addView(photo);
        }
    }

    private void setPrePhot(int h, int w, ImageView photo){
        if (h > 700 || w > 700){
            h = (int) (h / 1.5);
            w = (int) (w / 1.5);
            setPrePhot(h, w, photo);
            return;
        }
        ShapeDrawable line = new ShapeDrawable(new RectShape());
        line.setIntrinsicHeight(h);
        line.setIntrinsicWidth(w);
        line.getPaint().setColor(0x00000000);
        photo.setImageDrawable(line.getCurrent());
    }

    private View inflate(LinearLayout conteiner, int resId) {

        View v = inflater.inflate(resId, conteiner, false);
        conteiner.addView(v);
        return v;
    }

    @Override
    protected void onResume() {
        super.onResume();
        VKUIHelper.onResume(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        VKUIHelper.onDestroy(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        VKUIHelper.onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        //Handle config changes here, paying attention to
        //the newConfig.orientation value
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void addJSONObject(JSONObject json) {

        try {
            JSONObject response = json.getJSONObject("response");
            if ("post".equals(type)) {
                fillContent(response);
            } else {
                fillComms(response);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void fillComms(JSONObject response) {

        JSONArray items = response.optJSONArray("items");
        Map<String, Object> profMap = null;
        if (items != null){
            JSONArray profiles = response.optJSONArray("profiles");
            try {
                profMap = MyJsonHelper.toMap(profiles, "id");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for (int i=0; i < items.length(); i++){
                try {
                    JSONObject item  = (JSONObject) items.get(i);
                    LinearLayout rl_comCont = (LinearLayout) findViewById(R.id.pf_commentContainer);
                    View v = inflate(rl_comCont, R.layout.post_feed_comment);
                    long date = item.getLong("date");
                    HashMap profile = (HashMap)profMap.get(item.getString("from_id"));
                    String firstName = (String) profile.get("first_name");
                    String lastName = (String) profile.get("last_name");
                    String photo = (String) profile.get("photo_50");
                    String likes = item.getJSONObject("likes").getString("count");


                    ImageView avatar = (ImageView) v.findViewById(R.id.c_avatar);
                    Bitmap bm = imageCache.getBitmapFromMemCache(photo);
                    if (bm == null || bm.isRecycled()){
                        new ImageLoader(this, avatar).execute(photo);
                    } else {
                        avatar.setImageBitmap(bm);
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
                    ((TextView) v.findViewById(R.id.c_date)).setText(sdf.format(new Date(date * 1000)));
                    ((TextView) v.findViewById(R.id.c_name)).setText(firstName + " " + lastName);
                    ((TextView) v.findViewById(R.id.c_coment)).setText(item.getString("text"));
                    ((TextView) v.findViewById(R.id.c_likeCounts)).setText(likes);

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

    }

    @Override
    public void loadComplete() {

    }
}
