package app.fedilab.fedilabtube.services;
/* Copyright 2020 Thomas Schneider
 *
 * This file is a part of TubeLab
 *
 * 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.
 *
 * TubeLab 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 TubeLab; if not,
 * see <http://www.gnu.org/licenses>. */

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import net.gotev.uploadservice.ServerResponse;
import net.gotev.uploadservice.UploadInfo;
import net.gotev.uploadservice.UploadServiceBroadcastReceiver;

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

import java.util.ArrayList;

import app.fedilab.fedilabtube.helper.Helper;


public class PeertubeUploadReceiver extends UploadServiceBroadcastReceiver {


    @Override
    public void onProgress(Context context, UploadInfo uploadInfo) {
        // your code here
    }

    @Override
    public void onError(Context context, UploadInfo uploadInfo, ServerResponse serverResponse,
                        Exception exception) {
    }

    @SuppressLint("ApplySharedPref")
    @Override
    public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) {
        try {
            JSONObject response = new JSONObject(serverResponse.getBodyAsString());

            if (!response.has("video")) { //IT's not from Peertube
                ArrayList<String> file = uploadInfo.getSuccessfullyUploadedFiles();
                Intent addMedia = new Intent(Helper.INTENT_ADD_UPLOADED_MEDIA);
                addMedia.putExtra("response", serverResponse.getBodyAsString());
                addMedia.putStringArrayListExtra("uploadInfo", file);
                LocalBroadcastManager.getInstance(context).sendBroadcast(addMedia);
            } else {
                String videoID = response.getJSONObject("video").get("id").toString();
                SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(Helper.VIDEO_ID, videoID);
                editor.apply();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCancelled(Context context, UploadInfo uploadInfo) {
        // your code here
    }
}