package com.ttiglobal.inttilectgpchat;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.ttiglobal.inttilectgpchat.util.ApiService;
import com.ttiglobal.inttilectgpchat.util.GlobalData;
import com.ttiglobal.inttilectgpchat.util.MainApplication;
import com.ttiglobal.inttilectgpchat.util.MyCallback;
import com.ttiglobal.inttilectgpchat.util.TransparentProgressDialog;
import com.ttiglobal.inttilectgpchat.util.UtilService;
import com.ttiglobal.inttilectgpchat.wrappers.ContentFile;
import com.ttiglobal.inttilectgpchat.wrappers.ErrorResponse;
import com.ttiglobal.inttilectgpchat.wrappers.MyContent;
import com.ttiglobal.inttilectgpchat.wrappers.MyTopic;
import com.ttiglobal.inttilectgpchat.wrappers.TrainingCategory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import retrofit2.Call;
import retrofit2.Response;


public class WebViewActivity extends AppCompatActivity {
    public static MyContent CONTENT = new MyContent();
    public static MyTopic TOPIC = new MyTopic();
    public static TrainingCategory TRAINING_ID;
    private ProgressDialog pDialog;
    private TransparentProgressDialog progressDialog;

    TextView title;
    Toolbar toolbar;
    WebView webView;
    ApiService restService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        setupWindowAnimations();
        restService = ((MainApplication) getApplication()).getClient();
        File f = new File(Environment.getExternalStorageDirectory(), ".SUZUKI");
        if (!f.exists()) {
            f.mkdirs();
        }

        File f1 = new File(Environment.getExternalStorageDirectory() + "/" + ".SUZUKI", "WEB");
        if (!f1.exists()) {
            f1.mkdirs();
        }

        webView = findViewById(R.id.webView);
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                updateStatus();
            }
        });

        title = findViewById(R.id.title);
        title.setText(CONTENT.getTitle());
        title.setSelected(true);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        Objects.requireNonNull(getSupportActionBar()).setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadContentFile();
            }
        }, 1000);
    }

    private void updateStatus() {
        CONTENT.setStatus("2");
        if (new UtilService().isNetworkAvailable(WebViewActivity.this)) {
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("contentid", CONTENT.getContentid());
                map.put("assettopicid", CONTENT.getAssettopicid());
                map.put("status", "2");

                restService.updateContentStaus(map).enqueue(new MyCallback<ErrorResponse>("2") {
                    @Override
                    public void onResponse(Call<ErrorResponse> call, Response<ErrorResponse> response) {
                        if (response.body() != null && response.body().getStatus() == 200) {
                            CONTENT.setStatus(ids);
                        }
                    }

                    @Override
                    public void onFailure(Call<ErrorResponse> call, Throwable t) {

                    }
                });

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

    public boolean isFileAlreadyDownload(ContentFile contentFile) {
        String fileName = Environment.getExternalStorageDirectory()
                + "/" + ".SUZUKI/WEB/" + CONTENT.getContentid() + "_" + CONTENT.getVersion()
                + "_" + contentFile.getLanguage_code();
        File f = new File(fileName);
        return f.exists();
    }

    @SuppressLint("StaticFieldLeak")
    private void downloadZip() {
        new AsyncTask<Void, Integer, Void>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                try {
                    pDialog = new ProgressDialog(WebViewActivity.this);
                    pDialog.setTitle("");
                    pDialog.setMessage("Downloading...");
                    pDialog.setIndeterminate(false);
                    pDialog.setMax(100);
                    pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    pDialog.setCancelable(false);
                    pDialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            @Override
            protected Void doInBackground(Void... voids) {
                OutputStream output = null;
                InputStream input = null;
                try {
                    int count;
                    URL url = new URL(CONTENT.getContent_files().get(0).getFile_url());
                    URLConnection conection = url.openConnection();
                    conection.connect();
                    int lenghtOfFile = conection.getContentLength();
                    input = new BufferedInputStream(url.openStream(),
                            8192);
                    String fileName = Environment.getExternalStorageDirectory()
                            + "/" + ".SUZUKI/WEB/" + CONTENT.getContentid() + "_" + CONTENT.getVersion()
                            + "_" + CONTENT.getContent_files().get(0).getLanguage_code() + ".zip";
                    output = new FileOutputStream(fileName);
                    byte[] data = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        publishProgress((int) (total * 100 / lenghtOfFile));
                        output.write(data, 0, count);
                    }
                    output.flush();

                    File target = new File(Environment.getExternalStorageDirectory()
                            + "/" + ".SUZUKI/WEB/" + CONTENT.getContentid() + "_" + CONTENT.getVersion()
                            + "_" + CONTENT.getContent_files().get(0).getLanguage_code());
                    if (target.exists()) {
                        target.delete();
                    }
                    target.mkdir();
                    unzip(new File(fileName), target);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        Objects.requireNonNull(output).close();
                        Objects.requireNonNull(input).close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(Integer... progress) {
                super.onProgressUpdate(progress);
                pDialog.setProgress(progress[0]);
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                pDialog.dismiss();
                loadContentFile();
            }

        }.execute();

    }

    public static void unzip(File zipFile, File targetDirectory) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(
                new BufferedInputStream(new FileInputStream(zipFile)))) {
            ZipEntry ze;
            int count;
            byte[] buffer = new byte[8192];
            while ((ze = zis.getNextEntry()) != null) {
                File file = new File(targetDirectory, ze.getName());
                File dir = ze.isDirectory() ? file : file.getParentFile();
                if (!dir.isDirectory() && !dir.mkdirs())
                    throw new FileNotFoundException("Failed to ensure directory: " +
                            dir.getAbsolutePath());
                if (ze.isDirectory())
                    continue;
                try (FileOutputStream fout = new FileOutputStream(file)) {
                    while ((count = zis.read(buffer)) != -1)
                        fout.write(buffer, 0, count);
                }
            }
        }
    }

    public void loadContentFile() {
        try {
            title.setText(CONTENT.getTitle());
            if (isFileAlreadyDownload(CONTENT.getContent_files().get(0))) {
                File target = new File(Environment.getExternalStorageDirectory()
                        + "/" + ".SUZUKI/WEB/" + CONTENT.getContentid() + "_" + CONTENT.getVersion()
                        + "_" + CONTENT.getContent_files().get(0).getLanguage_code());
                progressDialog = new TransparentProgressDialog(WebViewActivity.this);
                progressDialog.show();
                webView.loadUrl("file:///" + target.getAbsolutePath() + "/story_html5.html");
            } else {
                downloadZip();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (GlobalData.canLogout) {
            finish();
        }
    }
}