package app.fedilab.fedilabtube;
/* 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.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;

import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationAction;
import net.gotev.uploadservice.UploadNotificationConfig;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import app.fedilab.fedilabtube.client.APIResponse;
import app.fedilab.fedilabtube.client.data.ChannelData;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.viewmodel.ChannelsVM;
import es.dmoral.toasty.Toasty;

import static app.fedilab.fedilabtube.MainActivity.peertubeInformation;
import static app.fedilab.fedilabtube.client.RetrofitPeertubeAPI.DataType.MY_CHANNELS;


public class PeertubeUploadActivity extends AppCompatActivity {


    private final int PICK_IVDEO = 52378;
    private final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 724;
    private Button set_upload_file, set_upload_submit;
    private Spinner set_upload_privacy, set_upload_channel;
    private TextView set_upload_file_name;
    private EditText video_title;
    private HashMap<String, String> channels;
    private Uri uri;
    private String filename;
    private HashMap<Integer, String> privacyToSend;
    private HashMap<String, String> channelToSend;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        setContentView(R.layout.activity_peertube_upload);

        set_upload_file = findViewById(R.id.set_upload_file);
        set_upload_file_name = findViewById(R.id.set_upload_file_name);
        set_upload_channel = findViewById(R.id.set_upload_channel);
        set_upload_privacy = findViewById(R.id.set_upload_privacy);
        set_upload_submit = findViewById(R.id.set_upload_submit);
        video_title = findViewById(R.id.video_title);

        ChannelsVM viewModelC = new ViewModelProvider(PeertubeUploadActivity.this).get(ChannelsVM.class);
        viewModelC.get(MY_CHANNELS, null).observe(PeertubeUploadActivity.this, this::manageVIewChannels);
        channels = new HashMap<>();
        setTitle(R.string.upload_video);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IVDEO && resultCode == Activity.RESULT_OK) {
            if (data == null || data.getData() == null) {
                Toasty.error(PeertubeUploadActivity.this, getString(R.string.toot_select_image_error), Toast.LENGTH_LONG).show();
                return;
            }
            set_upload_submit.setEnabled(true);

            uri = data.getData();

            String uriString = uri.toString();
            File myFile = new File(uriString);
            filename = null;
            if (uriString.startsWith("content://")) {
                Cursor cursor = null;
                try {
                    cursor = getContentResolver().query(uri, null, null, null, null);
                    if (cursor != null && cursor.moveToFirst()) {
                        filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    }
                } finally {
                    assert cursor != null;
                    cursor.close();
                }
            } else if (uriString.startsWith("file://")) {
                filename = myFile.getName();
            }
            if (filename == null) {
                filename = new Date().toString();
            }
            set_upload_file_name.setVisibility(View.VISIBLE);
            set_upload_file_name.setText(filename);

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void manageVIewChannels(APIResponse apiResponse) {
        if (apiResponse.getError() != null || apiResponse.getChannels() == null || apiResponse.getChannels().size() == 0) {
            if (apiResponse.getError() != null && apiResponse.getError().getError() != null)
                Toasty.error(PeertubeUploadActivity.this, apiResponse.getError().getError(), Toast.LENGTH_LONG).show();
            else
                Toasty.error(PeertubeUploadActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
            return;
        }

        //Populate channels
        List<ChannelData.Channel> channelsForUser = apiResponse.getChannels();
        String[] channelName = new String[channelsForUser.size()];
        String[] channelId = new String[channelsForUser.size()];
        int i = 0;
        for (ChannelData.Channel channel : channelsForUser) {
            channels.put(channel.getName(), channel.getId());
            channelName[i] = channel.getName();
            channelId[i] = channel.getId();
            i++;
        }

        channelToSend = new HashMap<>();
        channelToSend.put(channelName[0], channelId[0]);
        ArrayAdapter<String> adapterChannel = new ArrayAdapter<>(PeertubeUploadActivity.this,
                android.R.layout.simple_spinner_dropdown_item, channelName);
        set_upload_channel.setAdapter(adapterChannel);

        if (peertubeInformation == null) {
            return;
        }
        LinkedHashMap<String, String> translations = null;
        if (peertubeInformation.getTranslations() != null)
            translations = new LinkedHashMap<>(peertubeInformation.getTranslations());

        LinkedHashMap<Integer, String> privaciesInit = new LinkedHashMap<>(peertubeInformation.getPrivacies());
        Map.Entry<Integer, String> entryInt = privaciesInit.entrySet().iterator().next();
        privacyToSend = new HashMap<>();
        privacyToSend.put(entryInt.getKey(), entryInt.getValue());
        LinkedHashMap<Integer, String> privacies = new LinkedHashMap<>(peertubeInformation.getPrivacies());
        //Populate privacies
        String[] privaciesA = new String[privacies.size()];
        Iterator<Map.Entry<Integer, String>> it = privacies.entrySet().iterator();
        i = 0;
        while (it.hasNext()) {
            Map.Entry<Integer, String> pair = it.next();
            if (translations == null || translations.size() == 0 || !translations.containsKey(pair.getValue()))
                privaciesA[i] = pair.getValue();
            else
                privaciesA[i] = translations.get(pair.getValue());
            it.remove();
            i++;
        }

        ArrayAdapter<String> adapterPrivacies = new ArrayAdapter<>(PeertubeUploadActivity.this,
                android.R.layout.simple_spinner_dropdown_item, privaciesA);
        set_upload_privacy.setAdapter(adapterPrivacies);

        //Manage privacies
        set_upload_privacy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                LinkedHashMap<Integer, String> privaciesCheck = new LinkedHashMap<>(peertubeInformation.getPrivacies());
                Iterator<Map.Entry<Integer, String>> it = privaciesCheck.entrySet().iterator();
                int i = 0;
                while (it.hasNext()) {
                    Map.Entry<Integer, String> pair = it.next();
                    if (i == position) {
                        privacyToSend = new HashMap<>();
                        privacyToSend.put(pair.getKey(), pair.getValue());
                        break;
                    }
                    it.remove();
                    i++;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        set_upload_file.setEnabled(true);

        set_upload_file.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(PeertubeUploadActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
                    PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(PeertubeUploadActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                return;
            }
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("*/*");
            String[] mimetypes = {"video/*"};
            intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
            startActivityForResult(intent, PICK_IVDEO);

        });

        //Manage languages
        set_upload_channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                LinkedHashMap<String, String> channelsCheck = new LinkedHashMap<>(channels);
                Iterator<Map.Entry<String, String>> it = channelsCheck.entrySet().iterator();
                int i = 0;
                while (it.hasNext()) {
                    Map.Entry<String, String> pair = it.next();
                    if (i == position) {
                        channelToSend = new HashMap<>();
                        channelToSend.put(pair.getKey(), pair.getValue());

                        break;
                    }
                    it.remove();
                    i++;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        set_upload_submit.setOnClickListener(v -> {
            if (uri != null) {
                Map.Entry<String, String> channelM = channelToSend.entrySet().iterator().next();
                String idChannel = channelM.getValue();
                Map.Entry<Integer, String> privacyM = privacyToSend.entrySet().iterator().next();
                Integer idPrivacy = privacyM.getKey();

                try {
                    SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
                    String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
                    UploadNotificationConfig uploadConfig = new UploadNotificationConfig();
                    Intent in = new Intent(PeertubeUploadActivity.this, PeertubeEditUploadActivity.class);
                    PendingIntent clickIntent = PendingIntent.getActivity(PeertubeUploadActivity.this, 1, in, PendingIntent.FLAG_UPDATE_CURRENT);
                    uploadConfig
                            .setClearOnActionForAllStatuses(true);


                    uploadConfig.getProgress().message = getString(R.string.uploading);
                    uploadConfig.getCompleted().message = getString(R.string.upload_video_success);
                    uploadConfig.getError().message = getString(R.string.toast_error);
                    uploadConfig.getCancelled().message = getString(R.string.toast_cancelled);
                    uploadConfig.getCompleted().actions.add(new UploadNotificationAction(R.drawable.ic_baseline_check_24, getString(R.string.video_uploaded_action), clickIntent));

                    if (video_title != null && video_title.getText() != null && video_title.getText().toString().trim().length() > 0) {
                        filename = video_title.getText().toString().trim();
                    }
                    String uploadId = UUID.randomUUID().toString();
                    new MultipartUploadRequest(PeertubeUploadActivity.this, uploadId, "https://" + Helper.getLiveInstance(PeertubeUploadActivity.this) + "/api/v1/videos/upload")
                            .addFileToUpload(uri.toString().replace("file://", ""), "videofile")
                            .addHeader("Authorization", "Bearer " + token)
                            .setNotificationConfig(uploadConfig)
                            .addParameter("name", filename)
                            .addParameter("channelId", idChannel)
                            .addParameter("privacy", String.valueOf(idPrivacy))
                            .addParameter("nsfw", "false")
                            .addParameter("commentsEnabled", "true")
                            .addParameter("waitTranscoding", "true")
                            .setMaxRetries(3)
                            .startUpload();
                    finish();
                } catch (Exception exc) {
                    exc.printStackTrace();
                }
            }
        });
    }
}
