package io.lbry.browser.ui.publish;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.cardview.widget.CardView;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;

import com.arthenica.mobileffmpeg.Config;
import com.arthenica.mobileffmpeg.FFmpeg;
import com.arthenica.mobileffmpeg.FFprobe;

import com.arthenica.mobileffmpeg.Statistics;
import com.arthenica.mobileffmpeg.StatisticsCallback;
import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

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

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import io.lbry.browser.BuildConfig;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.InlineChannelSpinnerAdapter;
import io.lbry.browser.adapter.LanguageSpinnerAdapter;
import io.lbry.browser.adapter.LicenseSpinnerAdapter;
import io.lbry.browser.adapter.TagListAdapter;
import io.lbry.browser.listener.FilePickerListener;
import io.lbry.browser.listener.SdkStatusListener;
import io.lbry.browser.listener.StoragePermissionListener;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.Fee;
import io.lbry.browser.model.GalleryItem;
import io.lbry.browser.model.Language;
import io.lbry.browser.model.License;
import io.lbry.browser.model.NavMenuItem;
import io.lbry.browser.model.Tag;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.UpdateSuggestedTagsTask;
import io.lbry.browser.tasks.UploadImageTask;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.tasks.claim.ClaimResultHandler;
import io.lbry.browser.tasks.claim.PublishClaimTask;
import io.lbry.browser.tasks.lbryinc.LogPublishTask;
import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Predefined;
import io.lbry.lbrysdk.Utils;
import lombok.Data;
import lombok.Getter;

public class PublishFormFragment extends BaseFragment implements
        FilePickerListener, SdkStatusListener, StoragePermissionListener, TagListAdapter.TagClickListener, WalletBalanceListener {

    private static final String H264_CODEC = "h264";
    private static final int MAX_VIDEO_DIMENSION = 1920;
    private static final int MAX_BITRATE = 5000000; // 5mbps

    private boolean storageRefusedOnce;
    private static final int SUGGESTED_LIMIT = 8;

    private boolean editMode;
    @Getter
    private boolean saveInProgress;
    private String currentFilter;
    private boolean publishFileChecked;
    private boolean fetchingChannels;
    private boolean launchPickerPending;
    @Getter
    private boolean transcodeInProgress;
    private long transcodeStartTime;
    private VideoTranscodeTask videoTranscodeTask;

    private TextInputEditText inputTagFilter;
    private RecyclerView addedTagsList;
    private RecyclerView suggestedTagsList;
    private RecyclerView matureTagsList;
    private TagListAdapter addedTagsAdapter;
    private TagListAdapter suggestedTagsAdapter;
    private TagListAdapter matureTagsAdapter;
    private ProgressBar progressPublish;
    private ProgressBar progressLoadingChannels;
    private View noTagsView;
    private View noTagResultsView;

    private InlineChannelSpinnerAdapter channelSpinnerAdapter;
    private AppCompatSpinner channelSpinner;
    private AppCompatSpinner priceCurrencySpinner;
    private AppCompatSpinner languageSpinner;
    private AppCompatSpinner licenseSpinner;

    private NestedScrollView scrollView;
    private View layoutExtraFields;
    private TextView linkShowExtraFields;
    private View textNoPrice;
    private View layoutPrice;
    private SwitchMaterial switchPrice;
    private ImageView imageThumbnail;
    private TextView linkGenerateAddress;

    private TextInputEditText inputTitle;
    private TextInputEditText inputDescription;
    private TextInputEditText inputPrice;
    private TextInputEditText inputAddress;
    private TextInputEditText inputDeposit;
    private TextInputEditText inputOtherLicenseDescription;
    private TextInputLayout layoutOtherLicenseDescription;
    private View inlineDepositBalanceContainer;
    private TextView inlineDepositBalanceValue;
    private TextView textInlineAddressInvalid;

    private View linkPublishCancel;
    private MaterialButton buttonPublish;

    private View inlineChannelCreator;
    private TextInputEditText inlineChannelCreatorInputName;
    private TextInputEditText inlineChannelCreatorInputDeposit;
    private View inlineChannelCreatorInlineBalance;
    private TextView inlineChannelCreatorInlineBalanceValue;
    private View inlineChannelCreatorCancelLink;
    private View inlineChannelCreatorProgress;
    private MaterialButton inlineChannelCreatorCreateButton;

    private boolean uploading;
    private String lastSelectedThumbnailFile;
    private String uploadedThumbnailUrl;
    private boolean editFieldsLoaded;
    private boolean editChannelSpinnerLoaded;
    private Claim currentClaim;
    private GalleryItem currentGalleryItem;
    private String currentFilePath;
    private String transcodedFilePath;

    private View mediaContainer;
    private View uploadProgress;
    private CardView cardVideoOptimization;
    private ProgressBar optimizationRealProgress;
    private ProgressBar optimizationProgress;
    private TextView textOptimizationProgress;
    private TextView textOptimizationStatus;
    private TextView textOptimizationElapsed;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_publish_form, container, false);

        scrollView = root.findViewById(R.id.publish_form_scroll_view);
        progressLoadingChannels = root.findViewById(R.id.publish_form_loading_channels);
        progressPublish = root.findViewById(R.id.publish_form_publishing);
        channelSpinner = root.findViewById(R.id.publish_form_channel_spinner);
        mediaContainer = root.findViewById(R.id.publish_form_media_container);

        inputTagFilter = root.findViewById(R.id.form_tag_filter_input);
        noTagsView = root.findViewById(R.id.form_no_added_tags);
        noTagResultsView = root.findViewById(R.id.form_no_tag_results);

        textInlineAddressInvalid = root.findViewById(R.id.publish_form_inline_address_invalid);
        inlineDepositBalanceContainer = root.findViewById(R.id.publish_form_inline_balance_container);
        inlineDepositBalanceValue = root.findViewById(R.id.publish_form_inline_balance_value);

        cardVideoOptimization = root.findViewById(R.id.publish_form_video_opt_card);
        optimizationProgress = root.findViewById(R.id.publish_form_video_opt_progress);
        optimizationRealProgress = root.findViewById(R.id.publish_form_video_opt_real_progress);
        textOptimizationProgress = root.findViewById(R.id.publish_form_video_opt_progress_text);
        textOptimizationStatus = root.findViewById(R.id.publish_form_video_opt_status);
        textOptimizationElapsed = root.findViewById(R.id.publish_form_video_opt_elapsed);

        layoutExtraFields = root.findViewById(R.id.publish_form_extra_options_container);
        linkShowExtraFields = root.findViewById(R.id.publish_form_toggle_extra);
        layoutPrice = root.findViewById(R.id.publish_form_price_container);
        textNoPrice = root.findViewById(R.id.publish_form_no_price);
        switchPrice = root.findViewById(R.id.publish_form_price_switch);
        uploadProgress = root.findViewById(R.id.publish_form_thumbnail_upload_progress);
        imageThumbnail = root.findViewById(R.id.publish_form_thumbnail_preview);
        linkGenerateAddress = root.findViewById(R.id.publish_form_generate_address);

        inputTitle = root.findViewById(R.id.publish_form_input_title);
        inputDescription = root.findViewById(R.id.publish_form_input_description);
        inputPrice = root.findViewById(R.id.publish_form_input_price);
        inputAddress = root.findViewById(R.id.publish_form_input_address);
        inputDeposit = root.findViewById(R.id.publish_form_input_deposit);
        inputOtherLicenseDescription = root.findViewById(R.id.publish_form_input_license_other);
        layoutOtherLicenseDescription = root.findViewById(R.id.publish_form_license_other_layout);
        priceCurrencySpinner = root.findViewById(R.id.publish_form_currency_spinner);
        languageSpinner = root.findViewById(R.id.publish_form_language_spinner);
        licenseSpinner = root.findViewById(R.id.publish_form_license_spinner);

        linkPublishCancel = root.findViewById(R.id.publish_form_cancel);
        buttonPublish = root.findViewById(R.id.publish_form_publish_button);

        Context context = getContext();
        FlexboxLayoutManager flm1 = new FlexboxLayoutManager(context);
        FlexboxLayoutManager flm2 = new FlexboxLayoutManager(context);
        FlexboxLayoutManager flm3 = new FlexboxLayoutManager(context);
        addedTagsList = root.findViewById(R.id.form_added_tags);
        addedTagsList.setLayoutManager(flm1);
        suggestedTagsList = root.findViewById(R.id.form_suggested_tags);
        suggestedTagsList.setLayoutManager(flm2);

        root.findViewById(R.id.form_mature_tags_container).setVisibility(View.VISIBLE);
        matureTagsList = root.findViewById(R.id.form_mature_tags);
        matureTagsList.setLayoutManager(flm3);

        addedTagsAdapter = new TagListAdapter(new ArrayList<>(), context);
        addedTagsAdapter.setCustomizeMode(TagListAdapter.CUSTOMIZE_MODE_REMOVE);
        addedTagsAdapter.setClickListener(this);
        addedTagsList.setAdapter(addedTagsAdapter);

        suggestedTagsAdapter = new TagListAdapter(new ArrayList<>(), getContext());
        suggestedTagsAdapter.setCustomizeMode(TagListAdapter.CUSTOMIZE_MODE_ADD);
        suggestedTagsAdapter.setClickListener(this);
        suggestedTagsList.setAdapter(suggestedTagsAdapter);

        matureTagsAdapter = new TagListAdapter(Helper.getTagObjectsForTags(Predefined.PUBLISH_MATURE_TAGS), context);
        matureTagsAdapter.setCustomizeMode(TagListAdapter.CUSTOMIZE_MODE_ADD);
        matureTagsAdapter.setClickListener(this);
        matureTagsList.setAdapter(matureTagsAdapter);

        inlineChannelCreator = root.findViewById(R.id.container_inline_channel_form_create);
        inlineChannelCreatorInputName = root.findViewById(R.id.inline_channel_form_input_name);
        inlineChannelCreatorInputDeposit = root.findViewById(R.id.inline_channel_form_input_deposit);
        inlineChannelCreatorInlineBalance = root.findViewById(R.id.inline_channel_form_inline_balance_container);
        inlineChannelCreatorInlineBalanceValue = root.findViewById(R.id.inline_channel_form_inline_balance_value);
        inlineChannelCreatorProgress = root.findViewById(R.id.inline_channel_form_create_progress);
        inlineChannelCreatorCancelLink = root.findViewById(R.id.inline_channel_form_cancel_link);
        inlineChannelCreatorCreateButton = root.findViewById(R.id.inline_channel_form_create_button);

        initUi();

        return root;
    }

    private void initUi() {
        Context context = getContext();
        languageSpinner.setAdapter(new LanguageSpinnerAdapter(context, R.layout.spinner_item_generic));
        licenseSpinner.setAdapter(new LicenseSpinnerAdapter(context, R.layout.spinner_item_generic));

        licenseSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                License license = (License) adapterView.getAdapter().getItem(position);
                boolean otherLicense = Arrays.asList(
                        Predefined.LICENSE_COPYRIGHTED.toLowerCase(),
                        Predefined.LICENSE_OTHER.toLowerCase()).contains(license.getName().toLowerCase());
                Helper.setViewVisibility(layoutOtherLicenseDescription, otherLicense ? View.VISIBLE : View.GONE);
                if (!otherLicense) {
                    inputOtherLicenseDescription.setText(null);
                }
            }

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

            }
        });

        linkGenerateAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!editMode) {
                    inputAddress.setText(Helper.generateUrl());
                }
            }
        });

        switchPrice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                Helper.setViewVisibility(textNoPrice, checked ? View.GONE : View.VISIBLE);
                Helper.setViewVisibility(layoutPrice, checked ? View.VISIBLE : View.GONE);
            }
        });

        inputAddress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String value = Helper.getValue(charSequence);
                boolean invalid = !Helper.isNullOrEmpty(value) && !LbryUri.isNameValid(value);
                Helper.setViewVisibility(textInlineAddressInvalid, invalid ? View.VISIBLE : View.INVISIBLE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        inputDeposit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                Helper.setViewVisibility(inlineDepositBalanceContainer, hasFocus ? View.VISIBLE : View.GONE);
            }
        });

        linkShowExtraFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (layoutExtraFields.getVisibility() != View.VISIBLE) {
                    layoutExtraFields.setVisibility(View.VISIBLE);
                    linkShowExtraFields.setText(R.string.hide_extra_fields);
                    scrollView.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.fullScroll(NestedScrollView.FOCUS_DOWN);
                        }
                    });
                } else {
                    layoutExtraFields.setVisibility(View.GONE);
                    linkShowExtraFields.setText(R.string.show_extra_fields);
                }
            }
        });

        mediaContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkStoragePermissionAndLaunchFilePicker();
            }
        });

        channelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                Object item = adapterView.getItemAtPosition(position);
                if (item instanceof Claim) {
                    Claim claim = (Claim) item;
                    if (claim.isPlaceholder() && !claim.isPlaceholderAnonymous()) {
                        if (!fetchingChannels) {
                            showInlineChannelCreator();
                        }
                    } else {
                        hideInlineChannelCreator();
                    }
                }
            }

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

            }
        });

        inputTagFilter.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String value = Helper.getValue(charSequence);
                setFilter(value);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        linkPublishCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (transcodeInProgress) {
                    // show alert confirming the user is sure, and then cancel
                    FFmpeg.cancel();
                    transcodeInProgress = false;
                }

                Context context = getContext();
                if (context instanceof MainActivity) {
                    ((MainActivity) context).onBackPressed();
                }
            }
        });

        buttonPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (uploading) {
                    Snackbar.make(view, R.string.publish_thumbnail_in_progress, Snackbar.LENGTH_LONG).show();
                    return;
                } else if (Helper.isNullOrEmpty(uploadedThumbnailUrl)) {
                    showError(getString(R.string.publish_no_thumbnail));
                    return;
                }

                if (transcodeInProgress) {
                    Snackbar.make(view, R.string.optimization_in_progress, Snackbar.LENGTH_LONG).show();
                    return;
                }

                // check minimum deposit
                String depositString = Helper.getValue(inputDeposit.getText());
                double depositAmount = 0;
                try {
                    depositAmount = Double.valueOf(depositString);
                } catch (NumberFormatException ex) {
                    // pass
                    showError(getString(R.string.please_enter_valid_deposit));
                    return;
                }
                if (depositAmount < Helper.MIN_DEPOSIT) {
                    String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT));
                    showError(error);
                    return;
                }
                if (Lbry.walletBalance == null || Lbry.walletBalance.getAvailable().doubleValue() < depositAmount) {
                    showError(getString(R.string.deposit_more_than_balance));
                    return;
                }

                String priceString = Helper.getValue(inputPrice.getText());
                double priceAmount = Helper.parseDouble(priceString, 0);
                if (switchPrice.isChecked() && priceAmount == 0) {
                    showError(getString(R.string.price_amount_not_set));
                    return;
                }

                Claim claim = buildPublishClaim();
                if (validatePublishClaim(claim)) {
                    publishClaim(claim);
                }
            }
        });

        channelSpinnerAdapter = new InlineChannelSpinnerAdapter(getContext(), R.layout.spinner_item_channel, new ArrayList<>());
        channelSpinnerAdapter.addPlaceholder(false);
        setupInlineChannelCreator(
                inlineChannelCreator,
                inlineChannelCreatorInputName,
                inlineChannelCreatorInputDeposit,
                inlineChannelCreatorInlineBalance,
                inlineChannelCreatorInlineBalanceValue,
                inlineChannelCreatorCancelLink,
                inlineChannelCreatorCreateButton,
                inlineChannelCreatorProgress,
                channelSpinner,
                channelSpinnerAdapter
        );
    }

    @Override
    public void onStart() {
        super.onStart();
        MainActivity activity = (MainActivity) getContext();
        if (activity != null) {
            activity.hideSearchBar();
            activity.showNavigationBackIcon();
            activity.lockDrawer();
            activity.hideFloatingWalletBalance();

            activity.addFilePickerListener(this);
            activity.addWalletBalanceListener(this);

            activity.setActionBarTitle(editMode ? R.string.edit_content : R.string.new_publish);
        }
    }

    @Override
    public void onStop() {
        Context context = getContext();
        if (context instanceof MainActivity) {
            MainActivity activity = (MainActivity) getContext();
            activity.restoreToggle();
            activity.showFloatingWalletBalance();
            if (!MainActivity.startingFilePickerActivity) {
                activity.removeWalletBalanceListener(this);
                activity.removeFilePickerListener(this);
                activity.removeNavFragment(PublishFormFragment.class, NavMenuItem.ID_ITEM_NEW_PUBLISH);
                if (transcodeInProgress) {
                    FFmpeg.cancel();
                }
            }
        }

        super.onStop();
    }

    private void checkParams() {
        Map<String, Object> params = getParams();
        if (params != null) {
            if (params.containsKey("claim")) {
                Claim claim = (Claim) params.get("claim");
                if (claim != null && !claim.equals(this.currentClaim)) {
                    this.currentClaim = claim;
                    editFieldsLoaded = false;
                }
            } else if (params.containsKey("galleryItem")) {
                currentGalleryItem = (GalleryItem) params.get("galleryItem");
            } else if (params.containsKey("directFilePath")) {
                currentFilePath = (String) params.get("directFilePath");
            }

            if (this.currentClaim == null && params.containsKey("suggestedUrl")) {
                String suggestedUrl = (String) params.get("suggestedUrl");
                if (!Helper.isNullOrEmpty(suggestedUrl) && Helper.isNullOrEmpty(Helper.getValue(inputAddress.getText()))) {
                    Helper.setViewText(inputAddress, (String) params.get("suggestedUrl"));
                }
            }
        } else {
            // shouldn't actually happen
            cancelOnFatalCondition(getString(R.string.no_file_found));
        }
    }

    private void checkStoragePermissionAndLaunchFilePicker() {
        Context context = getContext();
        if (MainActivity.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, context)) {
            launchPickerPending = false;
            launchFilePicker();
        } else {
            launchPickerPending = true;
            MainActivity.requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    MainActivity.REQUEST_STORAGE_PERMISSION,
                    getString(R.string.storage_permission_rationale_images),
                    context,
                    true);
        }
    }

    private void launchFilePicker() {
        Context context = getContext();
        if (context instanceof MainActivity) {
            MainActivity.startingFilePickerActivity = true;
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.setType("image/*");
            ((MainActivity) context).startActivityForResult(
                    Intent.createChooser(intent, getString(R.string.select_thumbnail)),
                    MainActivity.REQUEST_FILE_PICKER);
        }
    }

    private void updateFieldsFromCurrentClaim() {
        if (currentClaim != null && !editFieldsLoaded) {
            Context context = getContext();
            try {
                Claim.StreamMetadata metadata = (Claim.StreamMetadata) currentClaim.getValue();
                if (context != null) {
                    uploadedThumbnailUrl = currentClaim.getThumbnailUrl(imageThumbnail.getLayoutParams().width, imageThumbnail.getLayoutParams().height, 85);
                }
                if (context != null && !Helper.isNullOrEmpty(uploadedThumbnailUrl)) {
                    Glide.with(context.getApplicationContext()).load(uploadedThumbnailUrl).centerCrop().into(imageThumbnail);
                }

                inputTitle.setText(currentClaim.getTitle());
                inputDescription.setText(currentClaim.getDescription());
                if (addedTagsAdapter != null && currentClaim.getTagObjects() != null) {
                    addedTagsAdapter.addTags(currentClaim.getTagObjects());
                    updateSuggestedTags(currentFilter, SUGGESTED_LIMIT, true);
                }

                if (metadata.getFee() != null) {
                    Fee fee = metadata.getFee();
                    switchPrice.setChecked(true);
                    inputPrice.setText(fee.getAmount());
                    priceCurrencySpinner.setSelection("lbc".equalsIgnoreCase(fee.getCurrency()) ? 0 : 1);
                }

                inputAddress.setText(currentClaim.getName());
                inputDeposit.setText(currentClaim.getAmount());

                if (metadata.getLanguages() != null && metadata.getLanguages().size() > 0) {
                    // get the first language
                    String langCode = metadata.getLanguages().get(0);
                    int langCodePosition = ((LanguageSpinnerAdapter) languageSpinner.getAdapter()).getItemPosition(langCode);
                    if (langCodePosition > -1) {
                        languageSpinner.setSelection(langCodePosition);
                    }
                }

                if (!Helper.isNullOrEmpty(metadata.getLicense())) {
                    LicenseSpinnerAdapter adapter = (LicenseSpinnerAdapter) licenseSpinner.getAdapter();
                    int licPosition = adapter.getItemPosition(metadata.getLicense());
                    if (licPosition == -1) {
                        licPosition = adapter.getItemPosition(Predefined.LICENSE_OTHER);
                    }
                    if (licPosition > -1) {
                        licenseSpinner.setSelection(licPosition);
                    }

                    License selectedLicense = (License) licenseSpinner.getSelectedItem();
                    boolean otherLicense = Arrays.asList(
                            Predefined.LICENSE_COPYRIGHTED.toLowerCase(),
                            Predefined.LICENSE_OTHER.toLowerCase()).contains(selectedLicense.getName().toLowerCase());
                    inputOtherLicenseDescription.setText(otherLicense ? metadata.getLicense() : null);
                }

                inputAddress.setEnabled(false);
                editMode = true;
                editFieldsLoaded = true;
            } catch (ClassCastException ex) {
                // invalid claim value type
                cancelOnFatalCondition(getString(R.string.publish_invalid_claim_type));
            }
        }
    }

    private void checkPublishFile() {
        if (publishFileChecked) {
            return;
        }

        String filePath = "";
        String thumbnailPath = null;
        if (currentGalleryItem != null) {
            // check gallery item type
            filePath = currentGalleryItem.getFilePath();
            thumbnailPath = currentGalleryItem.getThumbnailPath();
        } else if (currentFilePath != null) {
            filePath = currentFilePath;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            // file doesn't exist. although this shouldn't happen
            cancelOnFatalCondition(getString(R.string.no_file_found));
            return;
        }

        // check content type
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }

        boolean isVideo = false;
        boolean isImage = !Helper.isNullOrEmpty(type) && type.startsWith("image");
        if (!Helper.isNullOrEmpty(type) && type.startsWith("video")) {
            // ffmpeg video handling
            isVideo = true;
            if (!transcodeInProgress) {
                probeVideo(filePath);
            }
        }

        if (isVideo || isImage) {
            checkAndUploadThumbnail(filePath, thumbnailPath, isVideo ? "video" : "image");
        }

        Helper.setViewVisibility(cardVideoOptimization, isVideo ? View.VISIBLE : View.GONE);

        publishFileChecked = true;
    }

    private void checkAndUploadThumbnail(String filePath, String thumbnailPath, String type) {
        boolean thumbnailValid = false;
        if (!Helper.isNullOrEmpty(thumbnailPath)) {
            File file = new File(thumbnailPath);
            // make sure the file exists and it's not an empty file
            thumbnailValid = file.exists() && file.length() > 0;
        }

        if (!thumbnailValid) {
            createAndUploadThumbnail(filePath, type);
        } else {
            uploadThumbnail(thumbnailPath);
        }
    }

    private void createAndUploadThumbnail(String filePath, String type) {
        Context context = getContext();
        CreateThumbnailTask task = new CreateThumbnailTask(filePath, type, context, new CreateThumbnailTask.CreateThumbnailHandler() {
            @Override
            public void onSuccess(String thumbnailPath) {
                uploadThumbnail(thumbnailPath);
            }

            @Override
            public void onError(Exception error) {
                if (context != null) {
                    showError(getString(R.string.thumbnail_creation_failed));
                }
            }
        });
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    private void uploadThumbnail(String thumbnailPath) {
        if (uploading) {
            View view = getView();
            if (view != null) {
                Snackbar.make(view, R.string.wait_for_upload, Snackbar.LENGTH_LONG).show();
            }
            return;
        }

        Context context = getContext();
        if (context != null) {
            Glide.with(context.getApplicationContext()).load(thumbnailPath).centerCrop().into(imageThumbnail);
        }

        uploading = true;
        uploadedThumbnailUrl = null;
        UploadImageTask task = new UploadImageTask(thumbnailPath, uploadProgress, new UploadImageTask.UploadThumbnailHandler() {
            @Override
            public void onSuccess(String url) {
                lastSelectedThumbnailFile = thumbnailPath;
                uploadedThumbnailUrl = url;
                uploading = false;
            }

            @Override
            public void onError(Exception error) {
                View view = getView();
                if (context != null && view != null) {
                    showError(getString(R.string.image_upload_failed));
                }
                lastSelectedThumbnailFile = null;
                imageThumbnail.setImageDrawable(null);
                uploading = false;
            }
        });
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

