package com.clonejw.telecine.activities;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.android.volley.DefaultRetryPolicy;
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.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.clonejw.telecine.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

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

import java.util.ArrayList;
import java.util.List;

import static android.widget.Toast.LENGTH_LONG;
import static com.clonejw.telecine.activities.LogActivity.LOGIN_AUTOMATICO;

public class playingtvActivity extends AppCompatActivity {
    Context context;
    String videourl = "";
    int typ ;
    MyRecyclerViewAdapter adapter;
    ArrayList<String> footer = new ArrayList<>();
    ArrayList<String> id_movie = new ArrayList<>();
    ArrayList<String> titulo = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playingtv);



        SharedPreferences prefs = getSharedPreferences(LOGIN_AUTOMATICO, MODE_PRIVATE);

        final String idusuario= prefs.getString("idusuario", null);

        final String idVid = getIntent().getExtras().getString("idvid");
        final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        final String imei = telephonyManager.getDeviceId();


        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Resources resources;
                resources = getResources();
                String url = resources.getString(R.string.linksite)+"/api.php?action=imeicheck&token=1234567654343245516712738123&idc="+idusuario+"&imei="+imei;
                StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("strrrrsr", ">>>>>>>"+response);

                                JSONObject obj = null;
                                try {
                                    obj = new JSONObject(response);
                                    if(obj.getInt("validade") == 0){
                                        Toast.makeText(getApplicationContext(), "Limite Maximo de telas Atingido", Toast.LENGTH_LONG).show();
                                        finish();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                //displaying the error in toast if occurrs
                                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });

                //creating a request queue
                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
                requestQueue.add(stringRequest);
            }
        }, 10000);

        Resources resources0;
        resources0 = getResources();

        String url1 = resources0.getString(R.string.linksite)+"/api.php?action=logstatus&id="+idusuario+"&token=1234567654343245516712738123";
        StringRequest stringRequest1 = new StringRequest(Request.Method.GET, url1,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response1) {
                        JSONObject obj1 = null;
                        try {
                            obj1 = new JSONObject(response1);


                            if(obj1.getInt("validade") == 1){


                                String save = "";
                                if(idusuario != null){
                                    save = "&save=1&iduser="+idusuario;
                                }

                                Resources resources;
                                resources = getResources();
                                String url = resources.getString(R.string.linksite)+"/api.php?action=tv_view&token=1234567654343245516712738123&id="+idVid+save;
                                StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                                        new Response.Listener<String>() {
                                            @Override
                                            public void onResponse(String response) {


                                                Log.d("strrrrr", ">>>>>>>"+response);

                                                JSONObject obj = null;
                                                try {
                                                    obj = new JSONObject(response);

                                                    videourl = obj.get("link").toString();


                                                    VideoView videoView = (VideoView) findViewById(R.id.videoView);
                                                    videoView.setVisibility(View.VISIBLE);
                                                    Uri videouri = Uri.parse(videourl);
                                                    videoView.setVideoURI(videouri);
                                                    videoView.setMediaController(null);
                                                    videoView.setOnTouchListener(new View.OnTouchListener() {
                                                        @Override
                                                        public boolean onTouch(View view, MotionEvent motionEvent) {
                                                            return true;
                                                        }
                                                    });
                                                    videoView.start();



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


                                            }
                                        },
                                        new Response.ErrorListener() {
                                            @Override
                                            public void onErrorResponse(VolleyError error) {
                                                //displaying the error in toast if occurrs
                                                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                                            }
                                        });

                                //creating a request queue
                                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
                                requestQueue.add(stringRequest);
                            }else{

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


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occurrs
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        //creating a request queue
        RequestQueue requestQueue1 = Volley.newRequestQueue(getApplicationContext());
        requestQueue1.add(stringRequest1);





        Resources resources;
        resources = getResources();

        final String url4 = resources.getString(R.string.linksite)+"/api.php?action=tv&token=1234567654343245516712738123";
        JsonArrayRequest stringRequest4 = new JsonArrayRequest(Request.Method.GET, url4,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        try {


                            for(int i = 0; i <= response.length(); i++) {
                                JSONObject result1 = response.getJSONObject(i);
                                footer.add(result1.get("logo").toString());
                                id_movie.add(result1.get("id").toString());
                                titulo.add(result1.get("titulo").toString());


                            }



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

                        RecyclerView recyclerView4 = (RecyclerView) findViewById(R.id.canaistv);
                        LinearLayoutManager layoutManager
                                = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
                        recyclerView4.setScrollingTouchSlop(0);
                        recyclerView4.setLayoutManager(layoutManager);

                        adapter = new MyRecyclerViewAdapter(getApplicationContext(), footer, id_movie, titulo);

                        recyclerView4.setAdapter(adapter);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occurrs
                        Toast.makeText(getApplicationContext(), error.getMessage(), LENGTH_LONG).show();
                    }
                });
        stringRequest4.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueue requestQueue4 = Volley.newRequestQueue(getApplicationContext());
        requestQueue4.add(stringRequest4);

    }

    public static class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
        public static Context ctx;
        private List<String> mText;
        private List<String> mBack;
        private List<String> mId;
        private LayoutInflater mInflater;
        private MyRecyclerViewAdapter.ItemClickListener mClickListener;

        // data is passed into the constructor
        MyRecyclerViewAdapter(Context context, ArrayList<String> bg, ArrayList<String> id_movie, List<String> data) {
            this.mInflater = LayoutInflater.from(context);
            this.mText = data;
            this.mBack = bg;
            this.mId   = id_movie;
            this.ctx   = context;

        }

        // inflates the row layout from xml when needed
        @Override
        public MyRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mInflater.inflate(R.layout.card_tvs, parent, false);
            return new MyRecyclerViewAdapter.ViewHolder(view);
        }

        // binds the data to the TextView in each row
        @Override
        public void onBindViewHolder(MyRecyclerViewAdapter.ViewHolder holder, int position) {
            String animal = mBack.get(position);
            String idmovie= mId.get(position);
            String mtext  = mText.get(position);


            holder.myid.setText(idmovie);
            holder.mytext.setText(mtext);
            final int radius = 43;
            final int margin = 0;
            final Transformation transformation = new RoundedCornersTransformation(radius, margin);

            Picasso.get().load(animal).transform(transformation).into(holder.myTextView);
        }

        // total number of rows
        @Override
        public int getItemCount() {
            return mText.size();
        }


        // stores and recycles views as they are scrolled off screen
        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            ImageView myTextView;
            TextView myid;
            TextView mytext;
            Button play;


            ViewHolder(View itemView) {
                super(itemView);

                myid = itemView.findViewById(R.id.idvid);
                mytext=itemView.findViewById(R.id.text);
                myTextView = itemView.findViewById(R.id.imageView4);
                play = itemView.findViewById(R.id.playcard);



                itemView.setOnClickListener(this);
                play.setOnClickListener(this);
            }

            @Override
            public void onClick(View view) {


                Intent i = new Intent(ctx, playingtvActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                i.putExtra("idvid", myid.getText().toString());

                ctx.startActivity(i);





            }


        }



        // convenience method for getting data at click position
        String getItem(int id) {
            return mText.get(id);
        }

        // allows clicks events to be caught
        void setClickListener(MyRecyclerViewAdapter.ItemClickListener itemClickListener) {
            this.mClickListener = itemClickListener;
        }

        // parent activity will implement this method to respond to click events
        public interface ItemClickListener {
            void onItemClick(View view, int position);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        final RelativeLayout canais = (RelativeLayout) findViewById(R.id.canais);
         if(keyCode == 21){

                canais.setVisibility(View.VISIBLE);
                canais.dispatchSystemUiVisibilityChanged(View.VISIBLE);


         }else if(keyCode == 22){
             canais.setVisibility(View.INVISIBLE);
         }


        return super.onKeyDown(keyCode, event);
    }



}