package com.imofan.android.develop.sns;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import junit.framework.Assert;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.tencent.tauth.Tencent;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

/***
 * 开放平台工具类
 * 
 * @author poble
 * 
 */
public class MFSnsUtil {
    public final static int BUFFER = 1024;
    private static String TAG = "MFSnsUtil";
    private static final int MAX_DECODE_PICTURE_SIZE = 1920 * 1440;

    /**
     * 获取开放平台用户信息
     * 
     * @param platform
     * @param access_token
     * @param openid
     * @return
     */
    public static String getUserInfo(int platform, String access_token,
            String openid) {
        String url = null;
        String commonUrl = null;
        String queryString = null;
        switch (platform) {
        case MFSnsService.PLATFORM_SINA_WEIBO:
            url = MFSnsConfig.USER_INFO_URL_SINA;
            commonUrl = "access_token=" + access_token + "&uid=" + openid;
            queryString = "";
            break;
        case MFSnsService.PLATFORM_QQ_WEIBO:
            url = MFSnsConfig.USER_INFO_URL_TECENT2;
            commonUrl = "&oauth_consumer_key="
                    + MFSnsConfig.CONSUMER_KEY_TECENT + "&access_token="
                    + access_token + "&openid=" + openid;
            queryString = "format=json";
            break;
        case MFSnsService.PLATFORM_QQ_QZONE:
            url = MFSnsConfig.USER_INFO_URL_QZONE;
            commonUrl = "&oauth_consumer_key="
                    + MFSnsConfig.CONSUMER_KEY_TECENT + "&access_token="
                    + access_token + "&openid=" + openid;
            queryString = "format=json";
            break;
        default:
            break;
        }
        String result = "";
        try {
            result = MFSnsHttpUtil.httpGet(url, queryString + commonUrl);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 向平台发布文字微博(新浪微博，腾讯微博)
     * 
     * @param platform
     * @param content
     * @param access_token
     * @param openid
     * @return
     */
    public static String upload(int platform, String content,
            final String access_token, final String openid) {
        String result = "";
        switch (platform) {
        case MFSnsService.PLATFORM_SINA_WEIBO:
            result = uploadToSina(content, access_token, openid);
            break;
        case MFSnsService.PLATFORM_QQ_WEIBO:
            result = uploadToTecent(content, access_token, openid);
            break;
        case MFSnsService.PLATFORM_QQ_QZONE:
            // addShare(content, access_token, openid,"");
            break;
        default:
            break;
        }
        return result;
    }

    /**
     * 向新浪发送微博
     * 
     * @param content
     * @param access_token
     * @param openid
     * @return
     */
    public static String uploadToSina(String content,
            final String access_token, final String openid) {
        String url = "";
        String result = "";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        url = "https://api.weibo.com/2/statuses/update.json";
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("status", content));
        result = MFSnsHttpUtil.httpPost(url, params);
        result = parseSinaResult(result);
        return result;
    }
    /***
     * 新浪微博，添加关注
     * @param access_token
     * @param screen_name
     * @return
     */
    public static String addAttentionSina(final String access_token,
            final String screen_name) {
        String url = "";
        String result = "";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        url = "https://api.weibo.com/2/friendships/create.json";
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("screen_name", screen_name));
        result = MFSnsHttpUtil.httpPost(url, params);
        return result;
    }

    /**
     * 向腾讯发送文字微博
     * 
     * @param content  分享内容
     * @param access_token
     * @param openid
     * @return
     */
    public static String uploadToTecent(String content,
            final String access_token, final String openid) {
        String url = "";
        String result = "";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        url = "https://graph.qq.com/t/add_t";
        params.add(getValuePair("format", "json"));
        params.add(getValuePair("content", content));
        params.add(getValuePair("openid", openid));
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("oauth_consumer_key",
                MFSnsConfig.CONSUMER_KEY_TECENT));
        params.add(getValuePair("wei", ""));
        params.add(getValuePair("jing", ""));
        params.add(getValuePair("clientip", "154.211.45.1"));
        params.add(getValuePair("syncflag", "1"));
        result = MFSnsHttpUtil.httpPost(url, params);
        result = parseQQResult(result);
        return result;
    }

    /**
     * 发布一条带图片的微博
     * 
     * @param platform
     * @param content
     * @param access_token
     * @param openid
     * @param file
     * @return
     */
    public static String uploadWithPic(int platform, String content,
            final String access_token, final String openid, File file) {
        String result = "";
        switch (platform) {
        case MFSnsService.PLATFORM_SINA_WEIBO:
            result = uploadWithPicToSina(content, access_token, openid, file);
            break;
        case MFSnsService.PLATFORM_QQ_WEIBO:
            result = uploadWithPicToTencent(content, access_token, openid, file);
            break;
        case MFSnsService.PLATFORM_QQ_QZONE:
            break;
        default:
            break;
        }
        return result;
    }

    /**
     * 向新浪发送一条带图片的微博
     * 
     * @param content
     * @param access_token
     * @param openid
     * @param file
     * @return
     */
    public static String uploadWithPicToSina(String content,
            final String access_token, final String openid, File file) {
        String url = "";
        String result = "";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        url = "https://upload.api.weibo.com/2/statuses/upload.json";
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("status", content));
        result = MFSnsHttpUtil.httpPostWithPic(url, params, file);
        result = parseSinaResult(result);
        return result;
    }
    
   /***
    * 新浪微博转发微博
    * @param content  转发评论内容
    * @param access_token
    * @param id  转发微博id
    * @return
    */
    public static String repostToSina(String content,
            final String access_token, String id) {
        String url = "";
        String result = "";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        url = "https://api.weibo.com/2/statuses/repost.json";
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("id", id));
        if(null!=content&&!content.equals("")){
        	params.add(getValuePair("status", content));
        }
        result = MFSnsHttpUtil.httpPost(url, params);
        //Log.v("error_message:", result);
       // result = parseSinaResult(result);
        return result;
    }
    /**
     * 向腾讯发送一条带图片的微博
     * 
     * @param content
     * @param access_token
     * @param openid
     * @param file
     * @return
     */
    public static String uploadWithPicToTencent(String content,
            final String access_token, final String openid, File file) {
        String url = "";
        String result = "";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        url = "https://graph.qq.com/t/add_pic_t";
        params.add(getValuePair("format", "json"));
        params.add(getValuePair("content", content));
        params.add(getValuePair("openid", openid));
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("oauth_consumer_key",
                MFSnsConfig.CONSUMER_KEY_TECENT));
        params.add(getValuePair("wei", ""));
        params.add(getValuePair("jing", ""));
        params.add(getValuePair("clientip", "154.211.45.1"));
        params.add(getValuePair("syncflag", "1"));
        result = MFSnsHttpUtil.httpPostWithPic(url, params, file);
        result = parseQQResult(result);
        return result;
    }

    /**
     * 向qq空间分享
     * 
     * @param content
     *            分享文章内容
     * @param access_token
     * @param openid
     * @param imageUrl
     *            分享图片url
     * @param title
     *            分享文章标题
     * @param titleUrl
     *            分享文章链接
     * @return
     */
    public static String addShare(String content, final String access_token,
            final String openid, String imageUrl, String title, String titleUrl,String comment) {
        String url = "";
        String result = "";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        url = MFSnsConfig.ADD_SHARE_QZONE;
        params.add(getValuePair("format", "json"));
        params.add(getValuePair("openid", openid));
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("oauth_consumer_key",
                MFSnsConfig.CONSUMER_KEY_QZONE));
        params.add(getValuePair("title", title));
        params.add(getValuePair("url", titleUrl));
        params.add(getValuePair("comment", comment));// 评论
        params.add(getValuePair("summary", content));
        params.add(getValuePair("images", imageUrl));
        params.add(getValuePair("nswb", "1"));
        result = MFSnsHttpUtil.httpPost(url, params);
        result = parseQzoneResult(result);
        return result;
    }

    private static NameValuePair getValuePair(final String name,
            final String value) {
        NameValuePair pair = new NameValuePair() {
            @Override
            public String getValue() {
                return value;
            }

            @Override
            public String getName() {
                return name;
            }
        };
        return pair;
    }

    /**
     * 通过网络获取qq互联开放平台的用户id
     * 
     * @param access_token
     * @return
     */
    public static String getUserOpenId(String access_token) {
        String result = "";
        String openid = "";
        try {
            result = MFSnsHttpUtil.httpGet(MFSnsConfig.GET_OPENID_URL,
                    "access_token=" + access_token);
            int start = result.indexOf("{");
            int end = result.indexOf("}");
            result = result.substring(start, end + 1);
            JSONObject obj = new JSONObject(result);
            openid = obj.optString("openid");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return openid;
    }

    public static String getWeiBo(String access_token, String screenName) {
        String result = "";
        try {
            result = MFSnsHttpUtil.httpGet(
                    "https://api.weibo.com/2/statuses/user_timeline.json",
                    "access_token=" + access_token + "&screen_name="
                            + screenName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 检查平台是否已经认证
     * 
     * @param context
     * @param platform
     * @return
     */
    public static boolean isAuthorized(Context context, int platform) {
        SharedPreferences platforms = context.getSharedPreferences("platforms",
                0);
        String message = platforms.getString("platform" + platform, "");
        if (message.equals("")) {
            return false;
        } else {
            MFSnsUser user = parseUser(message);
            long expires_in = user.getExpire(); // 有效时间，秒
            long loginTime = user.getLoginTime(); // 登录时间，毫秒
            long overTime = System.currentTimeMillis() - loginTime;// 当前距登录时时间，毫秒
            if (overTime > ((expires_in - (30 * 60)) * 1000)) {// 将有效时间减去半小时
                return false;
            } else {
                return true;
            }
        }

    }

    /**
     * 获得平台认证用户信息
     * 
     * @param context
     * @param platform
     * @return
     */
    public static MFSnsUser getOpenUser(Context context, int platform) {
        SharedPreferences platforms = context.getSharedPreferences("platforms",
                0);
        String message = platforms.getString("platform" + platform, "");
        MFSnsUser user = parseUser(message);
        return user;
    }

    /**
     * 注销平台认证信息
     * 
     * @param context
     * @param platform
     * @return
     */
    public static boolean loginOut(Context context, int platform) {
        SharedPreferences platforms = context.getSharedPreferences("platforms",
                0);
        Editor editor = platforms.edit();// 获取编辑器
        editor.putString("platform" + platform, "");
        editor.commit();
        return true;
    }

    /**
     * 将本地存储的json数据转换成user对象
     * 
     * @param message
     * @return
     */
    private static MFSnsUser parseUser(String message) {
        if (null == message || "".equals(message)) {
            return null;
        }
        MFSnsUser user = null;
        try {
            JSONObject obj = new JSONObject(message);
            user = new MFSnsUser();
            user.setAccessToken(obj.optString("access_token"));
            user.setOpenId(obj.optString("openid"));
            user.setBrief(obj.optString("brief"));
            user.setNickname(obj.optString("nickname"));
            user.setExpire(obj.optLong("expires_in"));
            String[] icons = new String[] { obj.optString("icon_50"),
                    obj.optString("icon_180") };
            user.setIcons(icons);
            user.setLoginTime(obj.optLong("login_time"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 处理分享新浪后返回信息
     * 
     * @param result
     * @return
     */
    private static String parseSinaResult(String result) {
        String shareResult = "";
        try {
            JSONObject resultObj = new JSONObject(result);
            int errorCode = resultObj.optInt("error_code", 0);
            switch (errorCode) {
            case 0:// 分享成功
                shareResult = MFSnsShareListener.SHARE_RESULT_SUCCESS;
                break;
            case 400:// 分享内容重复
                shareResult = MFSnsShareListener.SHARE_RESULT_REPEAT;
                break;
            case 21316:// access_token过期无效
                shareResult = MFSnsShareListener.SHARE_RESULT_TOKEN_INVALID;
                break;
            case 20006:// 分享图片大小超出限制
                shareResult = MFSnsShareListener.SHARE_RESULT_IMAGE_TOO_LARGE;
                break;
            case 20005:// 分享图片类型错误
                shareResult = MFSnsShareListener.SHARE_RESULT_IMAGE_TYPE_ERROR;
                break;
            case 20012:// 分享文字字数超出限制
                shareResult = MFSnsShareListener.SHARE_RESULT_TEXT_TOO_LARGE;
                break;
            case 500:// 网络原因，出错
                shareResult = MFSnsShareListener.SHARE_RESULT_NET_ERROR;
                break;
            case 10023:// 分享频率太快，超出限制
                shareResult = MFSnsShareListener.SHARE_RESULT_OUT_SEND_LIMIT;
                break;
            default:// 分享失败
                shareResult = MFSnsShareListener.SHARE_RESULT_FAILED;
                break;
            }
        } catch (JSONException e) {
            shareResult = MFSnsShareListener.SHARE_RESULT_FAILED;
            e.printStackTrace();
        }
        return shareResult;
    }

    /**
     * 处理腾讯，返回信息处理
     * 
     * @param result
     * @return
     */
    private static String parseQQResult(String result) {
        String shareResult = "";
        try {
            JSONObject resultObj = new JSONObject(result);
            if (resultObj.optInt("error_code", 0) != 0) {
                shareResult = MFSnsShareListener.SHARE_RESULT_NET_ERROR;
            } else {
                int ret = resultObj.optInt("ret", -1);
                int errorCode = resultObj.optInt("errcode", -1);
                switch (ret) {
                case 0:// 分享成功
                    shareResult = MFSnsShareListener.SHARE_RESULT_SUCCESS;
                    break;
                case 4://
                    if (errorCode == 0) {
                        shareResult = MFSnsShareListener.SHARE_RESULT_SUCCESS;
                    } else if (errorCode == 8) {
                        shareResult = MFSnsShareListener.SHARE_RESULT_TEXT_TOO_LARGE;
                    } else if (errorCode == 10) {
                        shareResult = MFSnsShareListener.SHARE_RESULT_OUT_SEND_LIMIT;
                    }
                    break;
                case 3:// access_token过期无效
                    shareResult = MFSnsShareListener.SHARE_RESULT_TOKEN_INVALID;
                    break;
                default:// 分享失败
                    shareResult = MFSnsShareListener.SHARE_RESULT_FAILED;
                    break;
                }
            }

        } catch (JSONException e) {
            shareResult = MFSnsShareListener.SHARE_RESULT_FAILED;
            e.printStackTrace();
        }
        return shareResult;
    }

    /**
     * 处理腾讯，返回信息处理
     * 
     * @param result
     * @return
     */
    private static String parseQzoneResult(String result) {
        String shareResult = "";
        try {
            JSONObject resultObj = new JSONObject(result);
            if (resultObj.optInt("error_code", 0) != 0) {
                shareResult = MFSnsShareListener.SHARE_RESULT_NET_ERROR;
            } else {
                int ret = resultObj.optInt("ret", -1);
                switch (ret) {
                case 0:// 分享成功
                    shareResult = MFSnsShareListener.SHARE_RESULT_SUCCESS;
                    break;
                case 3021://
                    shareResult = MFSnsShareListener.SHARE_RESULT_REPEAT;
                    break;
                case 3028:
                    shareResult = MFSnsShareListener.SHARE_RESULT_OUT_SEND_LIMIT;
                    break;
                case 3:// access_token过期无效
                    shareResult = MFSnsShareListener.SHARE_RESULT_TOKEN_INVALID;
                    break;
                default:// 分享失败
                    shareResult = MFSnsShareListener.SHARE_RESULT_FAILED;
                    break;
                }
            }

        } catch (JSONException e) {
            shareResult = MFSnsShareListener.SHARE_RESULT_FAILED;
            e.printStackTrace();
        }
        return shareResult;
    }

    /***
     * 本地保存图片
     * 
     * @param url
     * @return
     */
    public static File saveImage(Context context,String url) {
       /* File sdcardDir = Environment.getDownloadCacheDirectory();//getExternalStorageDirectory();
        String path = sdcardDir.getPath() + "/mfcache";
        File dir = new File(sdcardDir, "mfcache");
        if (!dir.exists() || !dir.isDirectory()) {
            dir.mkdir();
        }*/
        InputStream is = null;
        OutputStream os = null;
        try {
            is = MFSnsHttpUtil.download(url);
            os = new FileOutputStream(new File(context.getDir("cacheImg", context.MODE_PRIVATE).getAbsolutePath(), "shareImg.cache"));
            byte buffer[] = new byte[BUFFER];
            int readSize = 0;
            while ((readSize = is.read(buffer)) > 0) {
                os.write(buffer, 0, readSize);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new File(context.getDir("cacheImg", context.MODE_PRIVATE).getAbsolutePath(), "shareImg.cache");
    }

    /***
     * 获取人人网用户id
     * @param access_token
     * @return
     * @throws JSONException
     */
    public static String postUserId(String access_token) throws JSONException {
        String result = "";
        String userId = "";
        Map<String, String> map = new HashMap<String, String>();
        map.put("method", "users.getLoggedInUser");
        map.put("v", "1.0");
        map.put("access_token", access_token);
        map.put("format", "JSON");

        String sign = MFSnsConfig.getSignature(map);

        // 请求人人网开放平台API服务器的地址
        String url = "http://api.renren.com/restserver.do";

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(getValuePair("method", "users.getLoggedInUser"));
        params.add(getValuePair("v", "1.0"));
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("format", "JSON"));
        params.add(getValuePair("sig", sign));
        result = MFSnsHttpUtil.httpPost(url, params);
        JSONObject obj = new JSONObject(result);
        userId = obj.optString("uid");
        return userId;
    }
    /***
     * 获取人人网用户信息
     * @param access_token
     * @param id
     * @return
     */
    public static String getRenRenUserMessage(String access_token, String id) {
        String result = "";
        String fields = "uid,name,sex,star,zidou,vip,birthday,tinyurl,headurl,mainurl";
        Map<String, String> map = new HashMap<String, String>();
        map.put("method", "users.getInfo");
        map.put("v", "1.0");
        map.put("access_token", access_token);
        map.put("format", "JSON");
        map.put("uids", id);
        map.put("fields", fields);

        String sign = MFSnsConfig.getSignature(map);

        // 请求人人网开放平台API服务器的地址
        String url = "http://api.renren.com/restserver.do";

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(getValuePair("method", "users.getInfo"));
        params.add(getValuePair("v", "1.0"));
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("format", "JSON"));
        params.add(getValuePair("uids", id));
        params.add(getValuePair("fields", fields));
        params.add(getValuePair("sig", sign));
        result = MFSnsHttpUtil.httpPost(url, params);
        return result;
    }
    /***
     * 向人人网发送新鲜事
     * @param access_token
     * @return
     * @throws JSONException
     */
    public static String senEventToRenRen(String access_token,String tittle,String content,String linkUrl,String imageUrl){
        String result = "";
        Long postId;
        Map<String, String> map = new HashMap<String, String>();
        map.put("method", "feed.publishFeed");
        map.put("v", "1.0");
        map.put("access_token", access_token);
        map.put("format", "JSON");
        if(tittle.length()>=30){
            tittle = tittle.substring(0, 30); 
        }
        map.put("name", tittle);
        map.put("description", content);
        map.put("url", linkUrl);
        if(null!=imageUrl&&!imageUrl.equals("")){
            map.put("image",imageUrl);
        }
        

        String sign = MFSnsConfig.getSignature(map);

        // 请求人人网开放平台API服务器的地址
        String url = "http://api.renren.com/restserver.do";

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(getValuePair("method", "feed.publishFeed"));
        params.add(getValuePair("v", "1.0"));
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("format", "JSON"));
        params.add(getValuePair("name", tittle));
        params.add(getValuePair("description",content));
        params.add(getValuePair("url",linkUrl));
        if(null!=imageUrl&&!imageUrl.equals(""))
        {
            params.add(getValuePair("image",imageUrl));
        }
        
        params.add(getValuePair("sig", sign));
        result = MFSnsHttpUtil.httpPost(url, params);
        JSONObject obj = null;
        try {
            obj = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String parasResult = "";
        int errorCode = obj.optInt("error_code",0);
        if(errorCode == 303){
            parasResult = MFSnsShareListener.SHARE_RESULT_OUT_SEND_LIMIT;
        }else if(errorCode ==0){
            postId = obj.optLong("post_id");
            if(postId>0){
                parasResult = MFSnsShareListener.SHARE_RESULT_SUCCESS;
            }else{
                parasResult = MFSnsShareListener.SHARE_RESULT_FAILED;
            } 
        }else{
            parasResult = MFSnsShareListener.SHARE_RESULT_FAILED;
        }
        return parasResult;
    }
    
    /***
     * 向人人网发送新鲜事
     * @param access_token
     * @return
     * @throws JSONException
     */
    public static String shareToRenRen(String access_token,String content,String linkUrl){
        String result = "";
        Long postId;
        Map<String, String> map = new HashMap<String, String>();
        map.put("method", "share.share");
        map.put("v", "1.0");
        map.put("access_token", access_token);
        map.put("format", "JSON");
        map.put("type", "6");
      
        map.put("comment", content);
        map.put("url", linkUrl);
       
        

        String sign = MFSnsConfig.getSignature(map);

        // 请求人人网开放平台API服务器的地址
        String url = "http://api.renren.com/restserver.do";

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(getValuePair("method", "share.share"));
        params.add(getValuePair("v", "1.0"));
        params.add(getValuePair("access_token", access_token));
        params.add(getValuePair("format", "JSON"));
        params.add(getValuePair("comment",content));
        params.add(getValuePair("url",linkUrl));
        params.add(getValuePair("type",6+""));
        
        params.add(getValuePair("sig", sign));
        result = MFSnsHttpUtil.httpPost(url, params);
        JSONObject obj = null;
        try {
            obj = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String parasResult = "";
        int errorCode = obj.optInt("error_code",0);
        if(errorCode == 303){
            parasResult = MFSnsShareListener.SHARE_RESULT_OUT_SEND_LIMIT;
        }else if(errorCode ==0){
            postId = obj.optLong("id");
            if(postId>0){
                parasResult = MFSnsShareListener.SHARE_RESULT_SUCCESS;
            }else{
                parasResult = MFSnsShareListener.SHARE_RESULT_FAILED;
            } 
        }else{
            parasResult = MFSnsShareListener.SHARE_RESULT_FAILED;
        }
        return parasResult;
    }
    /***
     * 将文件转换成字节数组
     * @param fileName
     * @param offset
     * @param len
     * @return
     */
    public static byte[] readFromFile(String fileName, int offset, int len) {
        if (fileName == null) {
            return null;
        }

        File file = new File(fileName);
        if (!file.exists()) {
            Log.i(TAG, "readFromFile: file not found");
            return null;
        }

        if (len == -1) {
            len = (int) file.length();
        }

        Log.d(TAG, "readFromFile : offset = " + offset + " len = " + len + " offset + len = " + (offset + len));

        if(offset <0){
            Log.e(TAG, "readFromFile invalid offset:" + offset);
            return null;
        }
        if(len <=0 ){
            Log.e(TAG, "readFromFile invalid len:" + len);
            return null;
        }
        if(offset + len > (int) file.length()){
            Log.e(TAG, "readFromFile invalid file len:" + file.length());
            return null;
        }

        byte[] b = null;
        try {
            RandomAccessFile in = new RandomAccessFile(fileName, "r");
            b = new byte[len]; // 创建合适文件大小的数组
            in.seek(offset);
            in.readFully(b);
            in.close();

        } catch (Exception e) {
            Log.e(TAG, "readFromFile : errMsg = " + e.getMessage());
            e.printStackTrace();
        }
        return b;
    }
    
    public static Bitmap extractThumbNail(final String path, final int height, final int width, final boolean crop) {
        Assert.assertTrue(path != null && !path.equals("") && height > 0 && width > 0);

        BitmapFactory.Options options = new BitmapFactory.Options();

        try {
            options.inJustDecodeBounds = true;
            Bitmap tmp = BitmapFactory.decodeFile(path, options);
            if (tmp != null) {
                tmp.recycle();
                tmp = null;
            }

            Log.d(TAG, "extractThumbNail: round=" + width + "x" + height + ", crop=" + crop);
            final double beY = options.outHeight * 1.0 / height;
            final double beX = options.outWidth * 1.0 / width;
            Log.d(TAG, "extractThumbNail: extract beX = " + beX + ", beY = " + beY);
            options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY) : (beY < beX ? beX : beY));
            if (options.inSampleSize <= 1) {
                options.inSampleSize = 1;
            }

            // NOTE: out of memory error
            while (options.outHeight * options.outWidth / options.inSampleSize > MAX_DECODE_PICTURE_SIZE) {
                options.inSampleSize++;
            }

            int newHeight = height;
            int newWidth = width;
            if (crop) {
                if (beY > beX) {
                    newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
                } else {
                    newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
                }
            } else {
                if (beY < beX) {
                    newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
                } else {
                    newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
                }
            }

            options.inJustDecodeBounds = false;

            Log.i(TAG, "bitmap required size=" + newWidth + "x" + newHeight + ", orig=" + options.outWidth + "x" + options.outHeight + ", sample=" + options.inSampleSize);
            Bitmap bm = BitmapFactory.decodeFile(path, options);
            if (bm == null) {
                Log.e(TAG, "bitmap decode failed");
                return null;
            }

            Log.i(TAG, "bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight());
            final Bitmap scale = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
            if (scale != null) {
                bm.recycle();
                bm = scale;
            }

            if (crop) {
                final Bitmap cropped = Bitmap.createBitmap(bm, (bm.getWidth() - width) >> 1, (bm.getHeight() - height) >> 1, width, height);
                if (cropped == null) {
                    return bm;
                }

                bm.recycle();
                bm = cropped;
                Log.i(TAG, "bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight());
            }
            return bm;

        } catch (final OutOfMemoryError e) {
            Log.e(TAG, "decode bitmap failed: " + e.getMessage());
            options = null;
        }

        return null;
    }
    
    
    /***
     * 保存某一平台选择状态
     * @param platform
     */
    public static void savePlatformSelected(Context context,int platform,String onOrOff){
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                "platform_state", Context.MODE_PRIVATE);
        Editor editor = sharedPreferences.edit();
        editor.putString("platform_state"+platform, onOrOff);
        editor.commit();// 提交修改
    }
    /***
     * 计算中英文混合时，占中文字符长度
     * @param value
     * @return
     */
    public   static   int   lengthOfQuanJiao(String   value)   { 
        if   (value   ==   null) 
                return   0; 

        StringBuffer   buff   =   new   StringBuffer(value); 
        float   length   =   0.0f; 
        String   stmp; 
        for   (int   i   =   0;   i   <   buff.length();   i++)   { 
                stmp   =   buff.substring(i,   i   +   1); 

                try   { 
                        stmp   =   new   String(stmp.getBytes( "utf8 ")); 
                }   catch   (Exception   e)   { 

                } 
                
                if   (stmp.getBytes().length   >   1)   { 
                        length   +=   1; 
                }   else   { 
                        length   +=   0.5f; 
                } 
        } 
        return   Math.round(length); 
    } 
}
