package com.itant.shiwushu.ui.detail;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.itant.shiwushu.R;
import com.itant.shiwushu.base.BaseSwipeActivity;
import com.itant.shiwushu.base.IPermission;
import com.itant.shiwushu.constant.CommonConstant;
import com.itant.shiwushu.manager.ToastManager;
import com.itant.shiwushu.tool.BitmapTool;
import com.itant.shiwushu.tool.PermissionTool;
import com.itant.shiwushu.tool.UriTool;

import java.io.File;
import java.io.FileNotFoundException;

import uk.co.senab.photoview.PhotoView;

/**
 * Created by 89003530 on 2017/4/19.
 */

public class PhotoActivity extends BaseSwipeActivity implements View.OnClickListener, IPermission {
    private static final int REQUEST_PHOTO = 1;
    private static final String[] PERMISSIONS_NECESSARY = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private PhotoView pv_meizhi;
    private Bitmap bitmap;
    public static final String KEY_URL = "image_url";
    private String fileName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_detail);

        pv_meizhi = findViewById(R.id.pv_meizhi);

        String url = getIntent().getStringExtra(KEY_URL);
        if (!TextUtils.isEmpty(url)) {
            findViewById(R.id.tv_save).setOnClickListener(this);
            fileName = url.substring(url.lastIndexOf("/"));
            Glide.with(this)
                    .load(url)
                    .apply(new RequestOptions()
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .placeholder(R.mipmap.logo)
                            .error(R.mipmap.logo)).listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    BitmapDrawable bitmapDrawable = (BitmapDrawable)resource;
                    if (bitmapDrawable != null) {
                        bitmap = bitmapDrawable.getBitmap();
                    }
                    pv_meizhi.setImageDrawable(resource);
                    return false;
                }
            }).into(pv_meizhi);

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_save:
                // 先判断有没有权限
                PermissionTool.initPermission(this,this, PERMISSIONS_NECESSARY, REQUEST_PHOTO);
                break;
        }
    }

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

    private void savePhoto() {
        // 保存图片到本地
        if (bitmap == null) {
            ToastManager.getInstance().toastShort("保存失败");
            return;
        }

        if (TextUtils.isEmpty(fileName)) {
            fileName = "lost&found.png";
        }
        String fullPath = Environment.getExternalStorageDirectory() + CommonConstant.PHOTO_SHIWUSHU + fileName;
        if (BitmapTool.saveBitmap(fullPath, bitmap)) {
            ToastManager.getInstance().toastShort("保存成功");
            //notifyPhotoUpdate(fullPath, "Lost&Found");
            insertIntoAlbum(fullPath, "Lost&Found") ;
        } else {
            ToastManager.getInstance().toastShort("保存失败");
        }
    }


    /**
     * 插入到相册，插入之后，文件名会自动命名为System.currentTimeMillis+文件后缀
     * @param picName
     */
    private void insertIntoAlbum(String fullPath, String picName) {
        File file = new File(fullPath);
        Uri uri = UriTool.getUriFromFile(this, CommonConstant.NAME_PROVIDE, file);

       try {
            MediaStore.Images.Media.insertImage(getContentResolver(), fullPath, picName, null);
            // 通知相册更新
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

            // 删除临时的
            file.delete();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通知更新，不知道为什么，如果是自己的文件夹，广播也不起作用
     * @param fullPath
     * @param picName
     */
    private void notifyPhotoUpdate(String fullPath, String picName) {
        File file = new File(fullPath);
        Uri uri = UriTool.getUriFromFile(this, CommonConstant.NAME_PROVIDE, file);
        // 通知相册更新
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
    }

    @Override
    public void onPermissionSuccess(int requestCode) {
        savePhoto();
    }

    @Override
    public void onPermissionFail(int requestCode) {
        ToastManager.getInstance().toastShort("权限被拒绝");
    }
}
