/*
 * DSBDirect
 * Copyright (C) 2019 Fynn Godau
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * This software is not affiliated with heinekingmedia GmbH, the
 * developer of the DSB platform.
 */

package godau.fynn.dsbdirect;

import android.content.Context;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
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.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.Objects;

public class DownloadManager {

    private Context mContext;
    private RequestQueue mQueue;

    public static final String RESPONSE_TOKEN = "token";
    public static final String RESPONSE_JSON = "json";
    public static final String RESPONSE_HTML = "html";

    public static final int RESPONSE_NO_CONTENT_REASON_NO_CONTENT = 0;
    public static final int RESPONSE_NO_CONTENT_REASON_INVALID_RESPONSE = 1;

    public DownloadManager(Context context) {
        mContext = context;
        mQueue = Volley.newRequestQueue(context);
    }

    public void downloadToken(String credentialsId, String credentialsPass, final Handler credentialsInvalidHandler,
                              final Handler credentialsCorrectHandler, Response.ErrorListener errorListener) {
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                mContext.getString(R.string.uri_auth, credentialsId, credentialsPass),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String authToken = response.replace("\"", "");

                        boolean credentialsInvalid = true;

                        // Check for invalid credentials
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                            credentialsInvalid = Objects.equals(authToken, "00000000-0000-0000-0000-000000000000");
                        } else {
                            credentialsInvalid = authToken == "00000000-0000-0000-0000-000000000000";
                        }

                        if (credentialsInvalid) {
                            credentialsInvalidHandler.sendEmptyMessage(0);
                        } else {
                            Utility.sendMessage(credentialsCorrectHandler, RESPONSE_TOKEN, authToken);
                        }
                    }
                }, errorListener);

        Log.d("DOWNLOAD", "downloading token");
        // Add request to RequestQueue
        mQueue.add(stringRequest);

    }

    public void downloadTimetableList(String authToken, final Handler noContentHandler, final Handler onResponseHandler,
                                      Response.ErrorListener errorListener) {
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                mContext.getString(R.string.uri_timetables, authToken),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Check for no content
                        try {
                            JSONArray jsonArray = new JSONArray(response);

                            String firstUri = jsonArray.getJSONObject(0).getString("timetableurl");

                            boolean noContent;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                noContent = Objects.equals(firstUri, "https://light.dsbcontrol.de/DSBlightWebsite/Homepage/NoContent.htm");
                            } else {
                                noContent = firstUri == "https://light.dsbcontrol.de/DSBlightWebsite/Homepage/NoContent.htm";
                            }

                            if (noContent) {
                                noContentHandler.sendEmptyMessage(RESPONSE_NO_CONTENT_REASON_NO_CONTENT);
                            } else {
                                Utility.sendMessage(onResponseHandler, RESPONSE_JSON, response);
                            }
                        } catch (JSONException e) {
                            // Response is invalid, so there probably is no content
                            noContentHandler.sendEmptyMessage(RESPONSE_NO_CONTENT_REASON_INVALID_RESPONSE);

                            e.printStackTrace();
                        }
                    }
                }, errorListener);

        Log.d("DOWNLOAD", "downloading timetable list");
        // Add request to RequestQueue
        mQueue.add(stringRequest);
    }

    public void downloadHtmlTable(final Table table, final FileManager fileManager, final Handler onDownloadedHandler, Response.ErrorListener errorListener) {
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                table.getUri(), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // Save file
                fileManager.saveFile(table, response);

                // Do something with file
                Utility.sendMessage(onDownloadedHandler, RESPONSE_HTML, response);
            }
        }, errorListener);

        Log.d("DOWNLOAD", "downloading html file at " + table.getUri());
        // Add request to RequestQueue
        mQueue.add(stringRequest);
    }

    public void downloadImageTable(final Table table, final FileManager fileManager, final Handler onDownloadedHandler, Response.ErrorListener errorListener) {
        ImageRequest imageRequest = new ImageRequest(table.getUri(), new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                fileManager.saveFile(table, response);
                onDownloadedHandler.sendEmptyMessage(0);
            }
        }, 0, 0, ImageView.ScaleType.FIT_CENTER, Bitmap.Config.RGB_565, errorListener);

        mQueue.cancelAll(new RequestQueue.RequestFilter() {
            @Override
            public boolean apply(Request<?> request) {
                return true;
            }
        });

        Log.d("DOWNLOAD", "downloading image file at " + table.getUri());
        // Add request to RequestQueue
        mQueue.add(imageRequest);
    }
}
