package com.clonejw.telecine.activities;


import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.VideoView;

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.StringRequest;
import com.android.volley.toolbox.Volley;
import com.clonejw.telecine.R;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.squareup.picasso.Picasso;

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

import static com.clonejw.telecine.activities.LogActivity.LOGIN_AUTOMATICO;

public class playingActivity extends AppCompatActivity {
    Context context;
    String videourl = "";
    int typ ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playing);
        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){

                                RelativeLayout access = (RelativeLayout) findViewById(R.id.access);
                                access.setVisibility(View.GONE);
                                String save = "";
                                if(idusuario != null){
                                    save = "&save=1&iduser="+idusuario;
                                }

                                Resources resources;
                                resources = getResources();
                                String url = resources.getString(R.string.linksite)+"/api.php?action=view&token=1234567654343245516712738123&idvid="+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("link1").toString();
                                                    if(obj.getInt("serv1") == 2){
                                                        typ = 2;
                                                        RelativeLayout exoplayervideo = (RelativeLayout) findViewById(R.id.exoplayervideo);
                                                        exoplayervideo.setVisibility(View.GONE);
                                                        WebView webview = (WebView) findViewById(R.id.webview);
                                                        WebSettings webSettings = webview.getSettings();
                                                        webSettings.setJavaScriptEnabled(true);
                                                        webSettings.setAppCacheEnabled(true);
                                                        webSettings.setAllowContentAccess(true);
                                                        webSettings.setAllowFileAccess(true);


                                                        webview.setWebViewClient(new WebViewClient());
                                                        webview.setWebChromeClient(new WebChromeClient(){});
                                                        CookieManager.getInstance().setAcceptCookie(true);
                                                        webview.getSettings().setMediaPlaybackRequiresUserGesture(true);
                                                        webSettings.setDomStorageEnabled(true);


                                                        webview.loadUrl(videourl);


                                                    }else {
                                                        typ = 3;
                                                        RelativeLayout webviewRelative = (RelativeLayout) findViewById(R.id.webviewRelative);
                                                        webviewRelative.setVisibility(View.GONE);
                                                        VideoView videoView = (VideoView) findViewById(R.id.videoView);

                                                        Uri videouri = Uri.parse(videourl);
                                                        videoView.setVideoURI(videouri);
                                                        MediaController mediaController = new
                                                                MediaController(playingActivity.this);
                                                        mediaController.setAnchorView(videoView);
                                                        videoView.setMediaController(mediaController);
                                                        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);


    }







}
