package com.example.foodinder_app;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.UiThread;
import android.support.v7.app.AppCompatActivity;
import android.util.Pair;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

public class Main3Activity extends AppCompatActivity {

    private ImageView image;
    private TextView text;
    int pom = 0;
    String photo=null;
    String name=null;
    private RequestQueue mQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        mQueue = Volley.newRequestQueue(this);

        image = (ImageView) findViewById(R.id.avatar3);
        text = (TextView) findViewById(R.id.name3);

        new Thread(new Runnable() {
            public void run() {
                while (photo==null) {
                    parseJSON();
                    SystemClock.sleep(1000);
                }

                Main3Activity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setCard();
                    }
                });
            }
        }).start();
    }

    private void setCard() {

        CardItem card = new CardItem(photo, name);
        image.setImageBitmap(card.getDrawable());
        text.setText(card.getName());

    }

    private void parseJSON() {
        String url = Swipper.api + "/exec?action=evaluate";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jarray = response.getJSONArray("item");

                            JSONObject jo = jarray.getJSONObject(0);

                            photo = jo.getString("photo");
                            name = jo.getString("name");

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


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                error.printStackTrace();
            }
        });


        mQueue.add(request);

    }
}
