package com.efounder.chat.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.efounder.chat.R;
import com.efounder.chat.model.ShareContent;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.FileUriUtil;
import com.utilcode.util.JFStringUtil;
import com.utilcode.util.LogUtils;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import static com.efounder.chat.service.MessageServiceZheng.TAG;

public class HandleShareIntentUtil {

    public static final int SHARE_TYPE_TEXT = 0;
    public static final int SHARE_TYPE_IMAGE = 1;
    public static final int SHARE_TYPE_WEB = 2;

    /**商城商品分享**/
    public static final int SHARE_TYPE_MALL_ITEM = 5;

    /**
     * 处理分享的intent，返回ShareContent，里面包含类型，分别处理
     * @param context context
     * @param intent intent
     * @return shareContent
     */
    public static ShareContent handleIntent(Context context, Intent intent) {
        String action = intent.getAction();
        String type = intent.getType();

        if (action!=null && action.equals(Intent.ACTION_SEND) && type!=null && type.startsWith("image/")) {
            if (intent.hasExtra(Intent.EXTRA_TEXT)){
                try {
                    return handleIntentForWeb(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            //单图
            return handleIntentForImage(context, intent, false);
        } else if (action!=null && action.equals(Intent.ACTION_SEND_MULTIPLE) && type != null && type.startsWith("image/")) {
            //多图
            return handleIntentForImage(context, intent, true);
        } else if (action !=null && action.equals(Intent.ACTION_SEND) && type != null && type.startsWith("text/")) {
            //文本
            try {
                return handleIntentForWeb(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 处理网址分享
     * @param intent intent
     * @return ShareContent
     */
    private static ShareContent handleIntentForWeb(Intent intent) throws Exception{

        String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
        String title = intent.getStringExtra(Intent.EXTRA_TITLE);
        String text = intent.getStringExtra(Intent.EXTRA_TEXT);
        String webUrl = null;
        //判断是否有网址
        if (intent.hasExtra("url")) {
            webUrl = intent.getStringExtra("url");
        } else if (!JFStringUtil.getCompleteUrl(text).equals("")) {
            //text字段是否包含网址
            webUrl = JFStringUtil.getCompleteUrl(text);
        }

        final ShareContent shareWeb = new ShareContent();
        if (webUrl != null) {
            //webUrl不为null，那么分享网页，类型为2
            shareWeb.setType(SHARE_TYPE_WEB);
            shareWeb.setUrl(webUrl);
            shareWeb.setText(text);

            //处理标题，如果有title，subject，则按顺序优先取，没有则用extraText
            if (title != null && !title.equals("")) {
                shareWeb.setSubject(title);
            } else if (subject != null && !subject.equals("")){
                shareWeb.setSubject(subject);
            } else {
                shareWeb.setSubject(text);
            }

            //处理图片
//            URL url = new URL(webUrl);
//            String protocol = url.getProtocol();
//            String domain = url.getHost();
//            shareWeb.setImgUrl(String.format("%s://%s%s", protocol, domain, "/favicon.ico"));
            final String url = webUrl;
            ThreadPoolUtils.execute(new ThreadPoolUtils.Task() {
                @Override
                protected void work() {
                    try {
                        shareWeb.setImgUrl(getIconUrlString(url));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });

        } else {
            //网址没有，纯文本类型 0
            shareWeb.setType(SHARE_TYPE_TEXT);
            shareWeb.setText(text);
        }
        return shareWeb;
    }

    /**
     * @param intent intent
     * @param isMulti 是否是多图
     */
    private static ShareContent handleIntentForImage(Context context, Intent intent, boolean isMulti) {
        ShareContent shareContent = new ShareContent();
        shareContent.setType(SHARE_TYPE_IMAGE);
        //接收多张图片
        ArrayList<Uri> uris = new ArrayList<>();
        if (isMulti) {
            uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        } else {
            Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
            uris.add(uri);
        }
        ArrayList<String> localPathList = new ArrayList<>();
        if (uris != null) {
            for (int i = 0; i < uris.size(); i++) {
                try {
                    String imagePath = FileUriUtil.getFilePathByUri(context, uris.get(i));
                    if (localPathList.size() >= 9) {
                        ToastUtil.showToast(context, R.string.wechatview_no_more_nine_image);
                        break;
                    }
                    if (imagePath!=null)
                    localPathList.add(imagePath);
                } catch (Exception e) {
                    ToastUtil.showToast(context, R.string.wechatview_get_image_info_fail);
                    e.printStackTrace();
                }
            }
            shareContent.setPictureList(localPathList);
        }
        shareContent.setText(ResStringUtil.getString(R.string.wrchatview_image_kh));
        return shareContent;
    }

    private static String getIconUrlString(String urlString) throws Exception {
        urlString = getFinalUrl(urlString);
        URL url = new URL(urlString);
        String iconUrl = url.getProtocol() + "://" + url.getHost() + "/favicon.ico";
        if (hasFavicon(iconUrl)) {
            return iconUrl;
        } else {
            //大部分网站做了移动端访问的适配，但wap类型的网址不一定有favicon
            String iconUrlNew = handleWapUrl(iconUrl);
            LogUtils.i(TAG, "handle wap url,before: " + iconUrl + "\n after: " + iconUrlNew);
            if (!TextUtils.equals(iconUrl, iconUrlNew) && hasFavicon(iconUrlNew)) {
                return iconUrlNew;
            }
        }
        return urlString;
    }

    private static boolean hasFavicon(String iconUrl) throws Exception{
        URL url = new URL(iconUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        return HttpURLConnection.HTTP_OK == connection.getResponseCode() && connection.getContentLength() > 0;
    }

    private static String getFinalUrl(String urlString) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            // 处理301/302重定向
            if (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM
                    || connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
                String location = connection.getHeaderField("Location");
                if (!location.contains("http")) {
                    location = urlString + "/" + location;
                }
                return location;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null)
                connection.disconnect();
        }
        return urlString;
    }

    /**
     * 处理某些网站专门针对wap适配的手机版例如淘宝https://m.taobao.com/#index
     * http://dynamic.m.tuniu.com/
     *
     * @param urlString
     * @return
     */
    private static String handleWapUrl(String urlString) throws MalformedURLException {
        if (!TextUtils.isEmpty(urlString) && urlString.contains("://m.")) {
            return urlString.replaceFirst("://m.", "://www.");
        }
        if (!TextUtils.isEmpty(urlString) && urlString.contains(".m.")) {
            URL url = new URL(urlString);
            return url.getProtocol() + "://www." + urlString.substring(urlString.indexOf(".m."));
        }
        return urlString;
    }
}
