package com.usai.util;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

import com.usai.apex.ApexTrackingApplication;
import com.usai.apex.R;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;


public class commonUtil {
    public static final int MY_PERMISSIONS_REQUEST = 1;
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);




    public static int dp2px(Context context, float dipValue)

    {

        float m=context.getResources().getDisplayMetrics().density ;

        return (int)(dipValue * m + 0.5f) ;

    }

    public static int sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int px2dp(Context context, float pxValue)

    {

        float m=context.getResources().getDisplayMetrics().density ;

        return (int)(pxValue / m + 0.5f) ;

    }


    public static Boolean checkPermissions(Activity activity, String[] permissions) {
        if (Build.VERSION.SDK_INT >= 23) {
            return checkPermissions_23(activity, permissions);
        } else {
            return false;
//            return checkPermissions_23(activity,permissions);
        }
    }

    public static Boolean checkPermissions_23(Activity activity, String[] permissions) {
        Log.d("_APEXMOBILE", "checkPermissions23:==================================== ");
        ArrayList<String> request_list = new ArrayList<String>();
        for (String permission : permissions) {
            boolean bshow = ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
//            boolean granted= ContextCompat.checkSelfPermission(activity,
//                    Manifest.permission.ACCESS_FINE_LOCATION)
//                    == PackageManager.PERMISSION_GRANTED;
            boolean pc = PermissionChecker.checkSelfPermission(activity, permission) == PermissionChecker.PERMISSION_GRANTED;
//            Log.d("_RAIMAGE", "checkPermissions23: "+permission+"  SHOW  "+bshow+"  granted  "+granted +","+pc);

            if (!pc)
                request_list.add(permission);
        }
        Log.d("_APEXMOBILE", "checkPermissions23:==================================== ");


        if (request_list.isEmpty())
            return false;
        ActivityCompat.requestPermissions(activity,
                request_list.toArray(new String[0]),
                MY_PERMISSIONS_REQUEST);


        return true;

    }
//	public static Boolean checkPermissions_24(Activity activity, String[] permissions)
//	{
//
//
//		if(permissions.length==0)
//			return true;
//		ActivityCompat.requestPermissions(activity,
//				permissions,
//				MY_PERMISSIONS_REQUEST);
//
//
//		return true;
//
//
//	}
//
//	public static Boolean checkPermissions_23(String[] permissions)
//	{
//		Log.d("_RAIMAGE", "checkPermissions23:==================================== ");
//		ArrayList<String> request_list = new ArrayList<String>();
//		Context context = ApexTrackingApplication.getInstance().getApplicationContext();
//		for(String permission : permissions) {
//
//			boolean pc = PermissionChecker.checkSelfPermission(context,permission)==PermissionChecker.PERMISSION_GRANTED;
//			if(!pc)
//				return false;
//		}
//		Log.d("_RAIMAGE", "checkPermissions23:==================================== ");
//
//
//
//		return true;
//
//	}

    public static int iconName2Rid(Context context,String name) {

        if (context == null) {
            context = ApexTrackingApplication.get_instance();
        }

        if (context == null || TextUtils.isEmpty(name)) {
            Log.d("null icon", "iconName2Rid context: "+(context==null)+" name isnull: "+(name == null) );

            return R.drawable.ic_launcher_new;
        }
        if(name.equals("Ocean Booking")|| name.equals("Booking Detail"))
            name = "mode_booking";
        if(name.equals("Ocean B/L info.")||name.equals("B/L info. Detail"))
            name = "mode_bl";
        if(name.equals("Container detail")||name.equals("Container Detail"))
            name = "mode_container";
        if(name.equals("Download Document"))
            name = "mode_document";
        if(name.equals("Cargo Tracking"))
            name = "mode_cargo_tracking";

        int iconid = context.getResources().getIdentifier(name, "drawable", context.getPackageName());

        return iconid;
    }

    public static boolean localdirExist() {

        File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/Apex Mobile");
        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }

    /**
     * Generate a value suitable for use in {@link #setId(int)}.
     * This value will not collide with ID values generated at build time by aapt for R.id.
     *
     * @return a generated ID value
     */
    public static int generateViewId() {
        for (; ; ) {
            final int result = sNextGeneratedId.get();
            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }

    public static String getDUID() {
        final TelephonyManager tm = (TelephonyManager) ApexTrackingApplication.get_instance().getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, androidId;
        String uniqueId;
        try {
            if (ActivityCompat.checkSelfPermission(ApexTrackingApplication.get_instance(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return null;
            }
            tmDevice = "" + tm.getDeviceId();
            tmSerial = "" + tm.getSimSerialNumber();
            androidId = "" + android.provider.Settings.Secure.getString(ApexTrackingApplication.get_instance().getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);
            UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
            uniqueId = deviceUuid.toString();
            Log.d("debug","uuid="+uniqueId);

        }
        catch(Exception e)
        {
            uniqueId= null;
        }
        return uniqueId;

		 }
}
