package com.sobot.album.app.fragment;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.sobot.album.AlbumFile;
import com.sobot.album.R;
import com.sobot.album.SobotAlbum;
import com.sobot.album.widget.photoview.AttacherImageView;
import com.sobot.album.widget.photoview.PhotoViewAttacher;
import com.sobot.common.utils.SobotImageUtils;
import com.sobot.common.utils.SobotPathManager;
import com.sobot.network.http.HttpBaseUtils;
import com.sobot.pictureframe.SobotBitmapUtil;
import com.sobot.utils.SobotDensityUtil;
import com.sobot.utils.SobotLogUtils;
import com.sobot.utils.SobotMD5Util;
import com.sobot.utils.SobotStringUtils;

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

public class ImageFragment extends Fragment implements PhotoViewAttacher.OnViewTapListener, View.OnLongClickListener {
    private View mRootView;
    private AttacherImageView imageView;
    public AlbumFile mAlbum;
    private View.OnClickListener mItemClickListener;
    private View.OnClickListener mItemLongClickListener;
    private String imageUrL;
    private Bitmap bitmap;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_img_item, container, false);
        imageView = mRootView.findViewById(R.id.sobot_item_iv);
        final PhotoViewAttacher attacher = new PhotoViewAttacher(imageView);
        attacher.setOnViewTapListener(this);
        attacher.setOnLongClickListener(this);
        imageView.setAttacher(attacher);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        initDate();
        return mRootView;
    }

    public static ImageFragment getInstance(AlbumFile mAlbum) {
        ImageFragment fragment = new ImageFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable("mAlbum", mAlbum);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setArguments(@Nullable Bundle bundle) {
        super.setArguments(bundle);
        if (bundle != null) {
            mAlbum = bundle.getParcelable("mAlbum");
        }
    }

    private void initDate() {
        if (mAlbum != null) {
            //设置地址
            if (SobotStringUtils.isNoEmpty( mAlbum.getPath())) {
                imageUrL = mAlbum.getPath();
            } else if(mAlbum.getUri()!=null){
                imageUrL = mAlbum.getUri().getPath();
            }else{
                imageUrL="";
            }
            if (imageUrL.startsWith("http")) {
                String dirPath = SobotPathManager.getInstance().getPicDir();
                String encode = SobotMD5Util.encode(imageUrL) + getFileName(imageUrL);
                File savePath = new File(SobotStringUtils.checkStringIsNull(dirPath), encode);
                if (!savePath.exists()) {
                    if (imageUrL.contains("?")) {
                        imageUrL = imageUrL.substring(0, imageUrL.indexOf("?"));
                    }
                    displayImage(imageUrL, savePath);
                } else {
                    showView(savePath.getAbsolutePath());
                }
            } else {
                File gifSavePath = new File(imageUrL);
                if (gifSavePath.exists()) {
                    showView(imageUrL);
                }
            }
        }
    }
    public String getFileName(String filePath) {
        try {
            if (filePath.indexOf("/") != -1) {
                return filePath.substring(filePath.lastIndexOf("/") + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    void showView(String savePath) {
        if (!TextUtils.isEmpty(imageUrL) && getContext()!=null) {
                bitmap = SobotBitmapUtil.compress(savePath, getContext(), true);
                //判断图片是否有旋转，有的话旋转后再显示
                try {
                    int degree = SobotImageUtils.readPictureDegree(savePath);
                    if (degree > 0) {
                        bitmap = SobotImageUtils.rotateBitmap(bitmap, degree);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                }
                imageView.setVisibility(View.VISIBLE);

                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        imageView.playSoundEffect(SoundEffectConstants.CLICK);
                    }
                });

        }
    }
    public void displayImage(String url, File saveFile) {
        // 下载图片
        HttpBaseUtils.getInstance().download(url, saveFile, new HttpBaseUtils.FileCallBack() {

            @Override
            public void onResponse(File file) {
                SobotLogUtils.i("down load onSuccess gif"
                        + file.getAbsolutePath());
                // 把图片文件打开为文件流，然后解码为bitmap
                showView(file.getAbsolutePath());
            }

            @Override
            public void onError(Exception e, String msg, int responseCode) {
                SobotLogUtils.w("图片下载失败:" + msg, e);
            }

            @Override
            public void inProgress(int progress) {
                //SobotLogUtils.i("图片下载进度:" + progress);
            }
        });
    }
    @Override
    public void onViewTap(View v, float x, float y) {
        if (mItemClickListener != null) {
            mItemClickListener.onClick(v);
        }
    }

    @Override
    public boolean onLongClick(View v) {
        if (mItemLongClickListener != null) {
            mItemLongClickListener.onClick(v);
        }
        return true;
    }

    /**
     * Set item click listener.
     *
     * @param onClickListener listener.
     */
    public void setItemClickListener(View.OnClickListener onClickListener) {
        this.mItemClickListener = onClickListener;
    }

    /**
     * Set item long click listener.
     *
     * @param longClickListener listener.
     */
    public void setItemLongClickListener(View.OnClickListener longClickListener) {
        this.mItemLongClickListener = longClickListener;
    }

}
