package com.dbs.mplus.fatima.framework.util;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.dbs.mplus.fatima.framework.MPlusFrameworkConstants;

import java.util.UUID;

import static android.content.Context.WIFI_SERVICE;

/**
 * @author hyeeun 
 */
public class MPlusDeviceUtil {
    private static boolean bInit;
    private static MPlusDeviceUtil deviceUtil;

    /**
     * 생성자
     */
    private MPlusDeviceUtil() {
        bInit = true;
    }

    /**
     * 인스턴스 생성
     * @return
     */
    public static MPlusDeviceUtil getInstance() {
        if(!bInit) {
            deviceUtil = new MPlusDeviceUtil();
        }


        return deviceUtil;
    }

    /**
     * 키보드 숨기기 
     * @param context
     * @param view
     */
    public void hideKeyBoard(Context context, View view) { 
		final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); 
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);     	
    }

    /**
     * 네트워크 사용가능 상태인지 여부 
     * @return
     */
    public boolean isOnline(Context context) { 
    	final ConnectivityManager m = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    	NetworkInfo net = null;

        if(Build.VERSION.SDK_INT < 23) {
            net = m.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if(net != null) { // wifi 전용 장비는 값이 null이 될 수 있음
                if(net.isConnectedOrConnecting()) {
                    return true;
                }
            }

            net = m.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if(net != null) { // wifi안되는 장비는 없겠지만 확인
                if(net.isConnectedOrConnecting()) {
                    return true;
                }
            }
        }
        else {
            net = m.getActiveNetworkInfo(); // 23에 추가된 메소드
            if(net != null) {
                switch (net.getType()) {
                    case ConnectivityManager.TYPE_WIFI:
                    case ConnectivityManager.TYPE_MOBILE:
                        return true;

                    default:
                        MPlusLogUtil.ERROR(MPlusDeviceUtil.class, "networkType : " + net.getType());
                        break;
                }
            }
        }
    	return false; 
    }

    /**
     * WIFI 연결체크
     * @param context
     * @param ssid
     * @return
     */
    public boolean checkWIFI(Context context, String ssid) {
        WifiManager manager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = manager.getConnectionInfo();
        String wifiSSID = wifiInfo.getSSID();
        MPlusLogUtil.DEBUG(MPlusDeviceUtil.class, "연결된 WIFI : " + wifiSSID);
        if(wifiSSID == null) {
            return false;
        }
        return wifiSSID.equals(ssid);
    }



    /**
     * device ID 가져오기 
     * @param context
     * @return
     */
    public static String getDeviceUUID(final Context context) {      
    	String id = null; 
    	
    	final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 
    	
    	// device ID 가져오기 
    	// - IMEI(International Mobile equipment Identity) for GSM,MEID or ESN for CDMA 
    	id = tm.getDeviceId(); 
    	// deviceID가 없거나 중복발행 오류가 있는 번호이면, android id를 사용 
    	if(id == null || MPlusFrameworkConstants.DUPLICATE_UUID.equals(id)) {
        	// android_id는 공장초기화하면 지워지는 값임 
        	id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); 	
        	if(id == null) { 
        		id = UUID.fromString(tm.getLine1Number()).toString(); 
        	}
    	}
    	
    	return id; 
    }

    /**
     * WIFI 연결여부 확인
     * @param context
     * @return
     */
    public static boolean isWIFIConnect(final Context context) {
        //Create object for ConnectivityManager class which returns network related info
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //If connectivity object is not null
        if (connectivity != null) {
            //Get network info - WIFI internet access
            NetworkInfo info = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (info != null) {
                //Look for whether device is currently connected to WIFI network
                if (info.isConnected()) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 앱 버전 확인 
     * @param context
     * @return
     */
    public static int getAppVersionName(final Context context) { 
    	PackageInfo pkgInfo = null; 
    	
    	try { 
    		pkgInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); 
    	}
    	catch(final NameNotFoundException ex) { 
    		MPlusLogUtil.ERROR(MPlusDeviceUtil.class, ex.getMessage());
    		return -1; 
    	}
    	
    	// 부주의에 의해 NumberFormatException이 발생할 수 있겠지만, 그냥 둔다. 
    	return Integer.parseInt(pkgInfo.versionName); 
    }
}
