package com.iuuaa.img.ui.fragments;

import android.Manifest;
import android.app.DownloadManager;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.customtabs.CustomTabsIntent;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatImageButton;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.iuuaa.common.annotation.Configuration;
import com.iuuaa.common.app.Request;
import com.iuuaa.common.customtabs.CustomTabsHelper;
import com.iuuaa.img.PixelsApplication;
import com.iuuaa.img.R;
import com.iuuaa.img.data.DataManager;
import com.iuuaa.img.data.SubscriberCallBack;
import com.iuuaa.img.data.glide.CircularBitmapImageViewTarget;
import com.iuuaa.img.data.glide.GlideApp;
import com.iuuaa.img.data.model.Download;
import com.iuuaa.img.data.model.LikeResult;
import com.iuuaa.img.data.model.PhotoDetails;
import com.iuuaa.img.data.model.Photos;
import com.iuuaa.img.delegate.PhotoDelegate;
import com.iuuaa.img.ui.AnchorSheetBehavior;
import com.iuuaa.img.ui.BaseFragment;
import com.iuuaa.img.ui.activitys.LoginActivity;
import com.iuuaa.img.ui.anim.SpringAnimationType;
import com.iuuaa.img.ui.anim.SpringyAnimator;
import com.iuuaa.img.ui.fragments.dialog.StatsDialog;
import com.iuuaa.img.ui.fragments.dialog.WallpaperDialog;
import com.iuuaa.img.ui.widget.biv.loader.ImageLoader;
import com.iuuaa.img.ui.widget.biv.view.BigImageView;
import com.iuuaa.img.utils.UserUtils;
import com.jakewharton.rxbinding2.view.RxView;
import com.tendcloud.tenddata.TCAgent;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.ocpsoft.prettytime.PrettyTime;

import java.io.File;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;
import timber.log.Timber;

@Configuration(theme = R.style.Garras_Translucent_Detail)
public class PhotoFragment extends BaseFragment<PhotoDelegate> implements EasyPermissions.PermissionCallbacks {
    public static String EXTRA_KEY = "extra_key";
    private Photos mPhotos;

    @BindView(R.id.app_bar_layout)
    AppBarLayout mAppBarLayout;

    @BindView(R.id.preview_progress)
    ProgressBar mPreviewProgress;
    @BindView(R.id.big_image)
    BigImageView mBigImage;

    @BindView(R.id.user_txt)
    AppCompatTextView mUserTxt;
    @BindView(R.id.user_avatar)
    AppCompatImageView mUserAvatar;
    @BindView(R.id.indicator_btn)
    AppCompatImageButton mIndicatorBtn;
    @BindView(R.id.title_txt)
    AppCompatTextView mTitleTxt;

    @BindView(R.id.bottom_sheet)
    NestedScrollView mBottomSheet;

    @BindView(R.id.info_location)
    AppCompatTextView mInfoLocation;
    @BindView(R.id.info_date)
    AppCompatTextView mInfoDate;
    @BindView(R.id.info_likes)
    AppCompatTextView mInfoLikes;
    @BindView(R.id.info_downloads)
    AppCompatTextView mInfoDownloads;
    @BindView(R.id.info_color)
    AppCompatTextView mInfoColor;
    @BindView(R.id.detail_content)
    LinearLayout mDetailContent;
    @BindView(R.id.detail_progress)
    ProgressBar mDetailProgress;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.exif_dimensions)
    AppCompatTextView mExifDimensions;
    @BindView(R.id.exif_make)
    AppCompatTextView mExifMake;
    @BindView(R.id.exif_model)
    AppCompatTextView mExifModel;
    @BindView(R.id.exif_exposure)
    AppCompatTextView mExifExposure;
    @BindView(R.id.exif_aperture)
    AppCompatTextView mExifAperture;
    @BindView(R.id.exif_iso)
    AppCompatTextView mExifIso;
    @BindView(R.id.exif_focal_length)
    AppCompatTextView mExifFocalLength;
    Unbinder unbinder;

    private BottomSheetBehavior mAnchorBehavior;

    private Drawable mColorIcon;
    private Menu mPhotoMenu;

    private DataManager mDataManager;
    private boolean isLike;
    private String mLinksUrl = null;

    private enum ActionType {DOWNLOAD, WALLPAPER}

    private PhotoFragment.ActionType mCurrentAction;
    private WallpaperDialog mWallpaperDialog;

    private long downloadReference;

    private DownloadManager mDownloadManager;

    IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (null == getActivity()) return;
            long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (downloadReference == reference) {
                DownloadManager.Query query = new DownloadManager.Query().setFilterById(reference);
                Cursor cursor = mDownloadManager.query(query);
                if (cursor.moveToFirst()) {
                    int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    switch (status) {
                        case DownloadManager.STATUS_SUCCESSFUL:
                            getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, mDownloadManager.getUriForDownloadedFile(downloadReference)));
                            if (mCurrentAction == PhotoFragment.ActionType.WALLPAPER) {
                                Uri uri = mDownloadManager.getUriForDownloadedFile(downloadReference);
                                Intent wallpaperIntent = WallpaperManager.getInstance(getActivity()).getCropAndSetWallpaperIntent(uri);
                                startActivityForResult(wallpaperIntent, 13451);
                                mWallpaperDialog.setDownloadFinished();
                            } else if (mCurrentAction == PhotoFragment.ActionType.DOWNLOAD) {
                                showSnackbar(mBottomSheet, getString(R.string.photo_download_completed));
                            }
                            break;
                        case DownloadManager.STATUS_FAILED:
                            showSnackbar(mBottomSheet, getString(R.string.photo_download_failed));
                            break;
                        default:
                            break;
                    }
                }
                if (mCurrentAction == PhotoFragment.ActionType.WALLPAPER) {
                    mWallpaperDialog.dismiss();
                }
                cursor.close();
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        TCAgent.onPageEnd(getContext(), getClass().getName());
        if (null == getActivity()) return;
        getActivity().registerReceiver(receiver, filter);
    }

    @Override
    public void onPause() {
        super.onPause();
        TCAgent.onPageEnd(getContext(), getClass().getName());
        if (null == getActivity()) return;
        getActivity().unregisterReceiver(receiver);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Request request = getRequest();
        mPhotos = request.getParcelableExtra(PhotoFragment.EXTRA_KEY);
        mDataManager = new DataManager();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        if (null == mPhotoMenu) mPhotoMenu = menu;
        inflater.inflate(R.menu.menu_detail, menu);
    }

    private boolean isWallpaperAction = true;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (null == getActivity() || null == getContext()) return super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.action_like:
                if (null != mPhotos) {
                    if (UserUtils.isAuthorized()) {
                        isLike = !isLike;
                        onLikeOperation(mPhotos.id, isLike);
                    } else {
                        new AlertDialog.Builder(getActivity()).setCancelable(false).setMessage(getString(R.string.no_login)).setNeutralButton(getString(R.string.cancel), null).setNegativeButton(getString(R.string.login), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                                startActivity(new Intent(getActivity(), LoginActivity.class));
                            }
                        }).show();
                    }
                }
                return true;
            case R.id.action_wallpaper:
                if (null != mPhotos) {
                    isWallpaperAction = true;
                    getDownloadOperating();
                }
                return true;
            case R.id.action_view_on_unsplash:
                if (!TextUtils.isEmpty(mLinksUrl)) {
                    openCustomTabs(mLinksUrl + PixelsApplication.UNSPLASH_UTM_PARAMETERS);
                }
                return true;
            case R.id.action_share:
                if (!TextUtils.isEmpty(mLinksUrl)) {
                    Intent share = new Intent(Intent.ACTION_SEND);
                    share.setType("text/plain");
                    if (share.resolveActivity(getContext().getPackageManager()) != null) {
                        share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

                        share.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.unsplash_image));
                        share.putExtra(Intent.EXTRA_TEXT, mLinksUrl + PixelsApplication.UNSPLASH_UTM_PARAMETERS);

                        startActivity(Intent.createChooser(share, getString(R.string.share_via)));
                    }
                }
                return true;
            case R.id.action_stats:
                if (null != mPhotos) {
                    StatsDialog statsDialog = new StatsDialog();
                    statsDialog.setPhotoId(mPhotos.id);
                    statsDialog.show(getChildFragmentManager(), StatsDialog.class.getName());
                }
                return true;
            case R.id.action_download:
                if (null != mPhotos) {
                    isWallpaperAction = false;
                    getDownloadOperating();
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private static final String[] STORAGE =
            {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    private boolean hasStoragePermissions() {
        return null != getContext() && EasyPermissions.hasPermissions(getContext(), STORAGE);
    }

    @AfterPermissionGranted(101)
    private void getDownloadOperating() {
        if (hasStoragePermissions()) {
            downloadUrl();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage), 101, STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    private void openCustomTabs(String url) {
        if (null == getActivity()) return;
        CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();
        intentBuilder.setToolbarColor(Color.WHITE);
        intentBuilder.setSecondaryToolbarColor(Color.BLACK);
        intentBuilder.addDefaultShareMenuItem();
        intentBuilder.setShowTitle(true);
        intentBuilder.enableUrlBarHiding();

        CustomTabsIntent customTabsIntent = intentBuilder.build();
        String packageName = CustomTabsHelper.getPackageNameToUse(getActivity());
        customTabsIntent.intent.setPackage(packageName);
        customTabsIntent.launchUrl(getActivity(), Uri.parse(url));
    }

    private static final int DELAY = 100;

    private void setTranslate(View view, int delay) {
        SpringyAnimator s3 = new SpringyAnimator(SpringAnimationType.TRANSLATEY, 15, 5, getResources().getDisplayMetrics().heightPixels / 8, 0);
        s3.setDelay(delay);
        s3.startSpring(view);
    }

    @Override
    public void bindEvenListener(@Nullable Bundle savedInstanceState) {
        super.bindEvenListener(savedInstanceState);
        allowSwipeBack(false);
        unbinder = ButterKnife.bind(this, viewDelegate.getRootView());
        if (null == getActivity()) return;

        if (getActivity() != null && null != mPhotos) {
            Photos.User user = mPhotos.user;
            ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
            mToolbar.setTitle("");
            setTranslate(mToolbar, DELAY * 2);

            setupData(user);
        }

        mAnchorBehavior = BottomSheetBehavior.from(mBottomSheet);
        mAnchorBehavior.setHideable(false);
        mAnchorBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, @AnchorSheetBehavior.State int newState) {
                int resId = newState == AnchorSheetBehavior.STATE_EXPANDED ? R.drawable.ic_expand_more_24dp : R.drawable.ic_expand_less_24dp;
                mIndicatorBtn.setImageResource(resId);
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            }
        });

        setTranslate(mBottomSheet, DELAY * 3);
    }

    private void setupData(Photos.User user) {
        if (null == getActivity()) return;
        mColorIcon = ContextCompat.getDrawable(getActivity(), R.mipmap.ic_fiber_manual_record_white_18dp);

        mUserTxt.setText(getString(R.string.by_photo, user.name));
        setTranslate(mUserTxt, DELAY * 4);
        try {
            Date createdAt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss-HH:mm", Locale.getDefault()).parse(mPhotos.created_at);
            mTitleTxt.setText(getString(R.string.shoot_at, new PrettyTime().format(createdAt)));
        } catch (ParseException e) {
            Timber.e(e);
        }

        RequestBuilder<Bitmap> bitmapRequestBuilder = GlideApp.with(getActivity())
                .asBitmap()
                .load(user.profile_image.large)
                .error(R.mipmap.bg_dark_avatar_male_big_normal)
                .placeholder(R.mipmap.bg_dark_avatar_male_big_normal)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .fallback(R.mipmap.bg_dark_avatar_male_big_normal);
        bitmapRequestBuilder.into(new CircularBitmapImageViewTarget(getActivity(), mUserAvatar));

        RxView.clicks(mUserAvatar).compose(this.bindUntilEvent(FragmentEvent.DESTROY_VIEW)).throttleFirst(1, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                if (null != mPhotos && null != mPhotos.user) {
                    Request request = new Request(UserFragment.class);
                    request.putExtra(UserFragment.EXTRA_USER_NAME_KEY, mPhotos.user.username);
                    request.putExtra(UserFragment.EXTRA_NIKE_NAME_KEY, mPhotos.user.name);
                    startFragment(request);
                }
            }
        });

        setTranslate(mUserTxt, DELAY * 4);
        setTranslate(mUserTxt, DELAY * 5);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (null == getActivity() || null == mPhotos || null == mBigImage) return;
        loadPhotoById();
        mBigImage.setImageLoaderCallback(new ImageLoader.Callback() {
            @Override
            public void onCacheHit(File image) {
            }

            @Override
            public void onCacheMiss(File image) {
            }

            @Override
            public void onStart() {
            }

            @Override
            public void onProgress(int progress) {
            }

            @Override
            public void onFinish() {
                if (null != mPreviewProgress) mPreviewProgress.setVisibility(View.GONE);
            }

            @Override
            public void onSuccess(File image) {
                if (null != mPreviewProgress) mPreviewProgress.setVisibility(View.GONE);
            }

            @Override
            public void onFail(Exception e) {
                if (null != mPreviewProgress) mPreviewProgress.setVisibility(View.GONE);
            }
        });
        mBigImage.showImage(Uri.parse(mPhotos.urls.thumb), Uri.parse(mPhotos.urls.regular));
    }

    private void downloadImage(String url, PhotoFragment.ActionType actionType) {
        if (null == getActivity()) return;
        String filename = mPhotos.id + "_" + mPhotos.user.name + PixelsApplication.DOWNLOAD_PHOTO_FORMAT;
        mDownloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url))
                .setTitle(filename)
                .setDestinationInExternalPublicDir(PixelsApplication.DOWNLOAD_PATH, filename)
                .setVisibleInDownloadsUi(false)
                .setNotificationVisibility(actionType == PhotoFragment.ActionType.DOWNLOAD ? DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED : DownloadManager.Request.VISIBILITY_VISIBLE);

        request.allowScanningByMediaScanner();
        downloadReference = mDownloadManager.enqueue(request);
    }

    private String mDownloadLocation = null;

    private void downloadUrl() {
        if (TextUtils.isEmpty(mDownloadLocation)) {
            mPreviewProgress.setVisibility(View.VISIBLE);
            mDataManager.download(mPhotos.id).compose(this.<Response<Download>>bindUntilEvent(FragmentEvent.DESTROY))
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SubscriberCallBack<Download>() {
                @Override
                public void onSuccess(Download downloadResponse) {
                    mPreviewProgress.setVisibility(View.GONE);
                    String downloadLocation = downloadResponse.url;
                    mDownloadLocation = downloadLocation + PixelsApplication.UNSPLASH_UTM_PARAMETERS;
                    if (isWallpaperAction) {
                        mCurrentAction = PhotoFragment.ActionType.WALLPAPER;
                        mWallpaperDialog = new WallpaperDialog();
                        mWallpaperDialog.setListener(new WallpaperDialog.WallpaperDialogListener() {
                            @Override
                            public void onCancel() {
                                mDownloadManager.remove(downloadReference);
                            }
                        });
                        mWallpaperDialog.show(getChildFragmentManager(), WallpaperDialog.class.getName());
                        downloadImage(mDownloadLocation, PhotoFragment.ActionType.WALLPAPER);
                    } else {
                        mCurrentAction = PhotoFragment.ActionType.DOWNLOAD;
                        downloadImage(mDownloadLocation, PhotoFragment.ActionType.DOWNLOAD);
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    mPreviewProgress.setVisibility(View.GONE);
                }

                @Override
                public void onCompleted() {
                }
            });
        } else {
            if (isWallpaperAction) {
                mCurrentAction = PhotoFragment.ActionType.WALLPAPER;
                mWallpaperDialog = new WallpaperDialog();
                mWallpaperDialog.setListener(new WallpaperDialog.WallpaperDialogListener() {
                    @Override
                    public void onCancel() {
                        mDownloadManager.remove(downloadReference);
                    }
                });
                mWallpaperDialog.show(getChildFragmentManager(), WallpaperDialog.class.getName());
                downloadImage(mDownloadLocation, PhotoFragment.ActionType.WALLPAPER);
            } else {
                mCurrentAction = PhotoFragment.ActionType.DOWNLOAD;
                downloadImage(mDownloadLocation, PhotoFragment.ActionType.DOWNLOAD);
            }
        }
    }

    private void onLikeOperation(String id, boolean isLike) {
        Flowable<Response<LikeResult>> flowable = isLike ? mDataManager.like(id) : mDataManager.unlike(id);
        flowable.compose(this.<Response<LikeResult>>bindUntilEvent(FragmentEvent.DESTROY)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SubscriberCallBack<LikeResult>() {
            @Override
            public void onSuccess(LikeResult likeResult) {

            }

            @Override
            public void onFailure(Throwable t) {

            }

            @Override
            public void onCompleted() {

            }
        });
        updateHeartButton(isLike);
    }

    private void loadPhotoById() {
        mDataManager.details(mPhotos.id).compose(this.<Response<PhotoDetails>>bindUntilEvent(FragmentEvent.DESTROY)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SubscriberCallBack<PhotoDetails>() {
            @Override
            public void onSuccess(PhotoDetails photoDetails) {
                if (null == photoDetails) return;
                setupDetails(photoDetails);
            }

            @Override
            public void onFailure(Throwable t) {
            }

            @Override
            public void onCompleted() {
            }
        });
    }

    private void setExifIcon(AppCompatTextView exifView, @DrawableRes int id) {
        if (null == getActivity()) return;
        Drawable drawable = ContextCompat.getDrawable(getActivity(), id);
        if (drawable != null) {
            drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
            exifView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            exifView.setCompoundDrawablePadding(25);
        }
    }

    private void setupDetails(PhotoDetails details) {
        try {
            Date createdAt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss-HH:mm", Locale.getDefault()).parse(details.created_at);
            String country = "";
            String city = "";
            StringBuilder sb = new StringBuilder();
            sb.append(new PrettyTime().format(createdAt));
            if (null != details.location) {
                country = TextUtils.isEmpty(country) ? "" : details.location.country;
                city = TextUtils.isEmpty(city) ? "" : details.location.city;
                if (!TextUtils.isEmpty(country) || !TextUtils.isEmpty(city)) {
                    sb.append(getString(R.string.shooting, country, city));
                }
            }
            if (TextUtils.isEmpty(sb)) return;
            mTitleTxt.setText(sb.toString());
        } catch (ParseException e) {
            Timber.e(e);
        }

        mLinksUrl = details.links.html;
        PhotoDetails.Exif exif = details.exif;

        if (details.location != null) {
            if (details.location.city != null && details.location.country != null) {
                mInfoLocation.setText(String.valueOf(details.location.city + ", " + details.location.country));
            } else if (details.location.city != null) {
                mInfoLocation.setText(details.location.city);
            } else if (details.location.country != null) {
                mInfoLocation.setText(details.location.country);
            }
        } else {
            mInfoLocation.setText("-----");
        }
        setExifIcon(mInfoLocation, R.drawable.ic_location_on_black_24dp);

        mInfoDate.setText(details.created_at.split("T")[0]);
        setExifIcon(mInfoDate, R.mipmap.ic_date_range_black_24dp);

        mInfoLikes.setText(getString(R.string.likes, NumberFormat.getInstance(Locale.CANADA).format(details.likes)));
        setExifIcon(mInfoLikes, R.mipmap.ic_favorite_black_24dp);

        mColorIcon.setColorFilter(Color.parseColor(details.color), PorterDuff.Mode.SRC_IN);
        mInfoColor.setText(details.color);
        setExifIcon(mInfoColor, R.mipmap.ic_color_lens_black_24dp);

        mInfoDownloads.setText(getString(R.string.downloads, NumberFormat.getInstance(Locale.CANADA).format(details.downloads)));
        setExifIcon(mInfoDownloads, R.mipmap.ic_file_download_black_24dp);

        isLike = details.liked_by_user;
        updateHeartButton(isLike);
        // ExifInterface
        mExifDimensions.setText(details.width == 0 || details.height == 0 ? "-----" : getString(R.string.photo_dimensions) + ": " + details.width + " x " + details.height);
        setExifIcon(mExifDimensions, R.mipmap.ic_straighten_black_24dp);

        mExifMake.setText(exif.make == null ? "-----" : getString(R.string.camera_make) + ": " + exif.make);
        setExifIcon(mExifMake, R.mipmap.ic_image_black_24dp);

        mExifModel.setText(exif.model == null ? "-----" : getString(R.string.camera_model) + ": " + exif.model);
        setExifIcon(mExifModel, R.mipmap.ic_camera_alt_black_24dp);

        mExifExposure.setText(exif.exposure_time == null ? "-----" : getString(R.string.exposure_time) + ": " + exif.exposure_time);
        setExifIcon(mExifExposure, R.mipmap.ic_timelapse_black_24dp);

        mExifAperture.setText(exif.aperture == null ? "-----" : getString(R.string.aperture) + ": " + exif.aperture);
        setExifIcon(mExifAperture, R.mipmap.ic_camera_black_24dp);

        mExifIso.setText(exif.iso == 0 ? "-----" : getString(R.string.iso) + ": " + String.valueOf(exif.iso));
        setExifIcon(mExifIso, R.mipmap.ic_iso_black_24dp);

        mExifFocalLength.setText(exif.focal_length == null ? "-----" : getString(R.string.focal_length) + ": " + exif.focal_length);
        setExifIcon(mExifFocalLength, R.mipmap.ic_all_out_black_24dp);

        mDetailContent.setVisibility(View.VISIBLE);
        mDetailProgress.setVisibility(View.GONE);
    }

    private void updateHeartButton(boolean isLike) {
        if (null != mPhotoMenu && UserUtils.isAuthorized()) {
            MenuItem item = mPhotoMenu.getItem(1);
            item.setVisible(true);
            item.setIcon(isLike ? R.drawable.ic_favorite_red_24dp : R.drawable.ic_favorite_border_24dp);
            View likeMenuView = mToolbar.findViewById(R.id.action_like);
            if (null == likeMenuView) return;
            SpringyAnimator springHelper = new SpringyAnimator(SpringAnimationType.SCALEXY, 100, 4, 0, 1);
            springHelper.startSpring(likeMenuView);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onBackPressed() {
        int state = mAnchorBehavior.getState();
        if (state == AnchorSheetBehavior.STATE_COLLAPSED || state == AnchorSheetBehavior.STATE_HIDDEN) {
            finish();
        } else {
            mAnchorBehavior.setState(AnchorSheetBehavior.STATE_COLLAPSED);
        }
    }

    @Override
    protected Class<PhotoDelegate> getDelegateClass() {
        return PhotoDelegate.class;
    }
}