package fr.svpro.radiomercure;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.MenuItem;
import android.webkit.CookieManager;
import android.webkit.URLUtil;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;

public class MainActivity extends AppCompatActivity {

    private static final int WRITE_EXTERNAL_STORAGE_RC = 100;
    private WebView web;
    private String url, userAgent, contentDisposition, mimeType;
    private Dialog dialog;
    private TextView tv_close;
    private TextView tv_version;
    private static String versionName;
    private static final String NUMERO_TEL_RADIO = "+33375411456";
    private static final String URL_PLATEFORM = "https://podcast.radiomercure.fr";  //"https://www.radiomercure.fr/?playerbar-pageinicial";
    private static final String URL_STREAM = "https://live.radiomercure.fr/on-air/live";
    private MediaPlayerService player;
    boolean serviceBound = false;

    static {
        versionName = BuildConfig.VERSION_NAME;
    }

    //Navigation
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private Toolbar toolbar;

    @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast", "JavascriptInterface"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //menu
        navigationView = findViewById(R.id.navigation_drawer);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {

                // Navigation drawer item click listener
                switch (item.getItemId()) {
                    case R.id.live:
                        Toast.makeText(MainActivity.this, "Vous écoutez Radio Mercure en direct", Toast.LENGTH_SHORT).show();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            lectureAudio(URL_STREAM);
                        } else {
                            Toast.makeText(MainActivity.this, "Votre version d'Android n'est pas compatible", Toast.LENGTH_SHORT).show();
                        }
                        break;

                    case R.id.tel:
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + NUMERO_TEL_RADIO));
                        startActivity(intent);
                        break;

                    case R.id.mail:
                        Intent form_mail = new Intent(MainActivity.this,MailActivity.class);
                        startActivity(form_mail);
                        break;

                    case R.id.home:
                        web.loadUrl(URL_PLATEFORM);
                        break;

                    case R.id.exit:
                        System.exit(0);
                        break;

                    case R.id.podmap:
                        web.loadUrl(URL_PLATEFORM + "/map");
                        break;

                    case R.id.about:
                        dialog.show();
                        break;
                }

                drawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }
        });

        //toolbar
        toolbar = findViewById(R.id.toolBar);
        drawerLayout = findViewById(R.id.drawer_layout);
        toolbar.setTitle("Radio Mercure");

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();

//------Demande d'autorisation de désactiver l'optimisation de la batterie------//
        AlertDialog.Builder dialogOptBattery = new AlertDialog.Builder(this);
        dialogOptBattery.setMessage(R.string.dialog_battery_msg)
                .setTitle(R.string.dialog_battery_titre);

        dialogOptBattery.setPositiveButton(R.string.dialog_button_oui, (dialog12, id) -> {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
            //intent.setData(Uri.parse("package:"+ getApplicationInfo().packageName));
            startActivity(intent);

        });
        dialogOptBattery.setNegativeButton(R.string.dialog_button_non, (dialog1, id) -> {
            // User cancelled the dialog
            Toast.makeText(this, R.string.battery_annul, Toast.LENGTH_SHORT).show();
        });
        AlertDialog alertDialog = dialogOptBattery.create();

        PowerManager powerManager = (PowerManager) getApplicationContext().getSystemService(POWER_SERVICE);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (!powerManager.isIgnoringBatteryOptimizations(getApplication().getPackageName())) {
                alertDialog.show();
            }
        }
//------------------------------------------------------------------------------------------------//

        //WebBiew affichage du site
        web = findViewById(R.id.wv);
        web.setWebViewClient(new WebViewClient());
        web.getSettings().setUserAgentString("Mozilla/5.0 "+ getApplicationInfo().packageName);
        web.getSettings().setJavaScriptEnabled(true);
        web.getSettings().setAllowFileAccess(true);
        web.getSettings().setAllowFileAccessFromFileURLs(true);
        web.getSettings().setAllowUniversalAccessFromFileURLs(true);
        web.getSettings().setAppCacheEnabled(true);
        web.getSettings().setDatabaseEnabled(true);
        web.getSettings().setDomStorageEnabled(true);
        web.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        web.getSettings().setAppCachePath(web.getContext().getCacheDir().getAbsolutePath());
        web.getSettings().setUseWideViewPort(true);
        web.getSettings().setLoadWithOverviewMode(true);
        web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        //Log.w("AGENT", web.getSettings().getUserAgentString());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            web.getSettings().setAllowFileAccessFromFileURLs(true);
        }
        web.loadUrl(URL_PLATEFORM);

        web.setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
            MainActivity.this.url = url;
            MainActivity.this.userAgent = userAgent;
            MainActivity.this.contentDisposition = contentDisposition;
            MainActivity.this.mimeType = mimeType;

            String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
            if (ActivityCompat.checkSelfPermission(MainActivity.this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        WRITE_EXTERNAL_STORAGE_RC);
            } else {
                TelechargemntPodcast();
            }
        });

        createDialog();

    }

    private void createDialog()
    {
        dialog=new Dialog(this);
        dialog.setTitle(R.string.dialog_about_titre);
        dialog.setContentView(R.layout.about_dialog);

        tv_close= (TextView) dialog.findViewById(R.id.tv_close);
        tv_version = (TextView) dialog.findViewById(R.id.tv_version);
        tv_close.setOnClickListener(v -> dialog.dismiss());
        tv_version.setText(getString(R.string.app_version) + versionName);
    }



    private void TelechargemntPodcast() {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

        request.setMimeType(mimeType);
        //------------------------COOKIE!!------------------------
        String cookies = CookieManager.getInstance().getCookie(url);
        request.addRequestHeader("cookie", cookies);
        //------------------------COOKIE!!------------------------
        request.addRequestHeader("User-Agent", userAgent);
        request.setDescription("Téléchargement...");
        request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        dm.enqueue(request);

        Toast.makeText(getApplicationContext(), "Téléchargement de " + URLUtil.guessFileName(url, contentDisposition, mimeType), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == WRITE_EXTERNAL_STORAGE_RC) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                TelechargemntPodcast();
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (web.canGoBack()) {
            web.goBack();
        } else {
            super.onBackPressed();
            System.exit(0);
        }
    }

    private void reStart() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    //Binding this Client to the AudioPlayer Service
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
            player = binder.getService();
            serviceBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            serviceBound = false;
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.O)
    @SuppressLint("UseCompatLoadingForDrawables")
    private void lectureAudio(String chemin) {
        //Check is service is active
        if (!serviceBound) {
            Intent playerIntent = new Intent(this, MediaPlayerService.class);
            playerIntent.putExtra("media",chemin);
            startService(playerIntent);
            bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
            //Toast.makeText(this, "Lecture", Toast.LENGTH_SHORT).show();
        } else {
            onDestroy();
            reStart();

        }

    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putBoolean("ServiceState", serviceBound);
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        serviceBound = savedInstanceState.getBoolean("ServiceState");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serviceBound) {
            unbindService(serviceConnection);
            //service is active
            player.stopSelf();
        }
    }

}