package com.hc.model.FJYD;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Settings;

import com.orhanobut.logger.Logger;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 福建移动内容提供者
 */
public class FJYDContentProvider {

    private static final String URI_BASE = "content://stbconfig/authentication";
    private static final String URI_USER_NAME = "username";
    private static final String URI_EPG_VSC_SERVER = "epg_server";
    private static final String URI_USER_TOKEN = "user_token";

    private Context context;

    public FJYDContentProvider(Context context) {
        this.context = context;
    }

    /**
     * 获取业务账号
     */
    public String getUserName() {
        String userName = getValue(URI_USER_NAME);
        Logger.d("获取到的业务账号：%s", userName);
        return userName;
    }

    /**
     * 获取Host+Port
     *
     * @param needProtocol 是否需要协议字段，如果为true，则返回Protocol :// Host + Port
     */
    public String getAuthority(boolean needProtocol) {
        String url = getValue(URI_EPG_VSC_SERVER);
        Logger.d("原地址：%s", url);
        try {
            URL u = new URL(url);
            Logger.d("当前域名：%s", u.getAuthority());
            return needProtocol ? u.getProtocol() + "://" + u.getAuthority() : u.getAuthority();
        } catch (MalformedURLException e) {
            Logger.e(e.getCause(), e.getMessage());
            return getIP(url, needProtocol);
        }
    }

//    /**
//     * 获取Host
//     */
//    public String getHost() {
//        String url = getValue(URI_EPG_VSC_SERVER);
//        try {
//            URL u = new URL(url);
//            Logger.d("当前域名：%s", u.getHost());
//            return u.getHost();
//        } catch (MalformedURLException e) {
//            Logger.e(e.getCause(), e.getMessage());
//            return getIP(url, false);
//        }
//    }

//    /**
//     * 获取认证EPG/VSC地址
//     */
//    public String getEPGorVSCUrl() {
//        return getValue(URI_EPG_VSC_SERVER);
//    }

    /**
     * 获取token
     */
    public String getToken() {
        String token = getValue(URI_USER_TOKEN);
        Logger.d("Token：%s", token);
        return token;
    }

    private String getValue(String contentName) {
        String value = "";
        Uri uri = Uri.parse(URI_BASE);
        Cursor cursor = null;

        try {
            cursor =  context.getContentResolver().query(uri, null, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String name = cursor.getString(cursor.getColumnIndex("name"));
                    if (name.equals(contentName)) {
                        value = cursor.getString(cursor.getColumnIndex("value"));
                        break;
                    }
                }
            }
        } catch (Exception e) {
            Logger.e(e.getCause(), e.getMessage());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return value;
    }

    private String getIP(String url, boolean needProtocol) {
        //使用正则表达式过滤，
        String re = "((http|ftp|https)://)(([a-zA-Z0-9._-]+)|([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}))(([a-zA-Z]{2,6})|(:[0-9]{1,4})?)";
        String str = "";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(re);
        // 忽略大小写的写法
        // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(url);
        //若url==http://127.0.0.1:9040或www.baidu.com的，正则表达式表示匹配
        if (matcher.matches()) {
            str = url;
        } else {
            String[] split2 = url.split(re);
            if (split2.length > 1) {
                str = url.substring(0, url.length() - split2[1].length());
                if (!needProtocol) {
                    String[] split3 = str.split("//");
                    if (split3.length > 1) {
                        str = split3[1];
                    }
                }
            } else {
                str = split2[0];
            }
        }
        return str;
    }
}
