/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.efounder.chat.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.core.view.ViewCompat;
import androidx.appcompat.app.AlertDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.http.OKHttpUtils;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.imageselector.photoview.PhotoView;
import com.efounder.util.AppContext;
import com.efounder.utils.ResStringUtil;

import java.io.File;

/**
 * 下载显示大图
 *
 */
public class ShowBigImageActivity extends BaseActivity {

    private ProgressDialog pd;
    private PhotoView image;
    private int default_res = R.drawable.loading_image_background;
    private String localFilePath;
    private Bitmap bitmap;
    private boolean isDownloaded;
    private ProgressBar loadLocalPb;

    //	private ImageLoader imageLoader;
//	DisplayImageOptions options;
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_show_big_image);
        super.onCreate(savedInstanceState);
        //initImageLoad();
        image = (PhotoView) findViewById(R.id.image);
        ViewCompat.setTransitionName(image, "avatar");
        loadLocalPb = (ProgressBar) findViewById(R.id.pb_load_local);
        final Uri uri = getIntent().getParcelableExtra("uri");

        System.out.println("show big image uri:" + uri);

        //本地存在，直接显示本地的图片
        if (uri != null && new File(uri.getPath()).exists()) {

            LXGlideImageLoader.getInstance().displayImage(this, image, uri);

            //imageLoader.displayImage("file://"+uri.getPath(),image,options);
        } else if (uri == null) { //去服务器下载图片
            String path = getIntent().getStringExtra("path");
            //imageLoader.displayImage(path, image,options);
            LXGlideImageLoader.getInstance().displayImage(this, image, path);

            System.out.println("从服务器下载图片" + "path:" + path);

        } else {
            image.setImageResource(default_res);
        }
        final Handler mHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        Toast.makeText(AppContext.getCurrentActivity(), ResStringUtil.getString(R.string.chat_photo_save_to) +
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + ResStringUtil.getString(R.string.chat_under_catalog), Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(AppContext.getCurrentActivity(), ResStringUtil.getString(R.string.chat_photo_save_fail), Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(AppContext.getCurrentActivity(), ResStringUtil.getString(R.string.chat_photo_existed), Toast.LENGTH_SHORT).show();
                    default:
                        break;
                }
            }
        };
        image.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        image.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final AlertDialog dlg = new AlertDialog.Builder(ShowBigImageActivity.this).create();
                dlg.show();
                Window window = dlg.getWindow();
                window.setContentView(R.layout.alertdialog);
                TextView content1 = (TextView) window.findViewById(R.id.tv_content1);
                LinearLayout content2 = (LinearLayout) window.findViewById(R.id.ll_content2);
                content2.setVisibility(View.GONE);
                content1.setText(R.string.wrchatview_down_image);
                content1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            if (uri != null && new File(uri.getPath()).exists()) {
                                Toast.makeText(ShowBigImageActivity.this, ResStringUtil.getString(R.string.chat_photo_save_to) + uri.getPath().substring(0, uri.getPath().lastIndexOf("/")) + "目录下", Toast.LENGTH_SHORT).show();
                            } else if (uri == null) {
                                String url = getIntent().getStringExtra("path");
//								String fileName = url.substring(url.lastIndexOf("/"), url.length())+".png";
//								File file = new File(ImageUtil.CHATPICTRE+fileName);

                                File picPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                                if (!picPath.exists()) {
                                    picPath.mkdirs();
                                }

                                String fileName = String.valueOf(System.currentTimeMillis()) + ".png";
                                final File file = new File(picPath.getAbsolutePath(), fileName);
                                if (!file.exists()) {
                                    OKHttpUtils.downLoadFiles(AppContext.getCurrentActivity(), 2, url, file.getAbsolutePath(), null, new OKHttpUtils.DownloadListener() {
                                        @Override
                                        public void onSuccess(String path) {
                                            mHandler.sendEmptyMessage(1);
                                            ImageUtil.galleryAddPic(path);
                                        }

                                        @Override
                                        public void onFailure() {
                                            mHandler.sendEmptyMessage(2);
                                        }
                                    });
                                } else {
                                    mHandler.sendEmptyMessage(3);
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        dlg.dismiss();
                    }
                });
                return false;
            }
        });
    }

//	private void initImageLoad() {
//		// 初始化异步加载图片的类
//		imageLoader = ImageLoader.getInstance();
//
//		//单独配置options
//		// 设置异步加载图片的配置信息
//		options = new DisplayImageOptions.Builder()
//				.showImageForEmptyUri(default_res) // empty
//				// URI时显示的图片
//				.showImageOnFail(default_res) // 不是图片文件
//				// 显示图片
//				.resetViewBeforeLoading(false) // default
//				.delayBeforeLoading(1).cacheInMemory(false) // default 不缓存至内存
//				.cacheOnDisk(true) // default 不缓存至手机SDCard
//				.bitmapConfig(Bitmap.Config.RGB_565)// RGB_565模式消耗的内存比ARGB_8888模式少两倍.
//				.build();
//	}

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

//	/**
//	 * 通过远程URL，确定下本地下载后的localurl
//	 * @param remoteUrl
//	 * @return
//	 */
//	public String getLocalFilePath(String remoteUrl){
//		String localPath;
//		if (remoteUrl.contains("/")){
//			localPath = ImageUtil.chatpath
//					+ remoteUrl.substring(remoteUrl.lastIndexOf("/") + 1);
//		}else{
//			localPath = ImageUtil.chatpath  + remoteUrl;
//		}
//		return localPath;
//	}
//
//	/**
//	 * 下载图片
//	 *
//	 * @param remoteFilePath
//	 */
//	private void downloadImage(final String remoteFilePath, final Map<String, String> headers) {
//		pd = new ProgressDialog(this);
//		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//		pd.setCanceledOnTouchOutside(false);
//		pd.setMessage("下载图片: 0%");
//		pd.show();
//		localFilePath = getLocalFilePath(remoteFilePath);
//		final HttpFileManager httpFileMgr = new HttpFileManager(this, EMChatConfig.getInstance().getStorageUrl());
//		final CloudOperationCallback callback = new CloudOperationCallback() {
//			public void onSuccess(String resultMsg) {
//
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						DisplayMetrics metrics = new DisplayMetrics();
//						getWindowManager().getDefaultDisplay().getMetrics(metrics);
//						int screenWidth = metrics.widthPixels;
//						int screenHeight = metrics.heightPixels;
//
//						bitmap = ImageUtils.decodeScaleImage(localFilePath, screenWidth, screenHeight);
//						if (bitmap == null) {
//							image.setImageResource(default_res);
//						} else {
//							image.setImageBitmap(bitmap);
//						//	ImageCache.getInstance().put(localFilePath, bitmap);
//							isDownloaded = true;
//						}
//						if (pd != null) {
//							pd.dismiss();
//						}
//					}
//				});
//			}
//
//			public void onError(String msg) {
//				Log.e("###", "offline file transfer error:" + msg);
//				File file = new File(localFilePath);
//				if (file.exists()&&file.isFile()) {
//					file.delete();
//				}
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						pd.dismiss();
//						image.setImageResource(default_res);
//					}
//				});
//			}
//
//			public void onProgress(final int progress) {
//				Log.d("ease", "Progress: " + progress);
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						pd.setMessage("下载图片: " + progress + "%");
//					}
//				});
//			}
//		};
//
//		new Thread(new Runnable() {
//			@Override
//			public void run() {
//				httpFileMgr.downloadFile(remoteFilePath, localFilePath, headers, callback);
//			}
//		}).start();
//	}
//
//	@Override
//	public void onBackPressed() {
//		if (isDownloaded)
//			setResult(RESULT_OK);
//		finish();
//	}
}
