package com.tomas.ht_mast.lib.common;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

public class Utils {
    public static void hideKeyboardFrom(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    public static boolean isVisible(final View view) {
        if (view == null) {
            return false;
        }
        if (!view.isShown()) {
            return false;
        }
        final Rect actualPosition = new Rect();
        view.getGlobalVisibleRect(actualPosition);
        final Rect screen = new Rect(0, 0,
                Resources.getSystem().getDisplayMetrics().widthPixels,
                Resources.getSystem().getDisplayMetrics().heightPixels);
        return actualPosition.intersect(screen);
    }


    public static boolean CompareDouble(Double a, Double b) { return Math.abs(a-b) < 0.000001; }
    public static void clearForm(ViewGroup group) {
        for (int i = 0, count = group.getChildCount(); i < count; ++i) {
            View view = group.getChildAt(i);
            if (view instanceof EditText) {
                ((EditText)view).setText("");
            }

            if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
                clearForm((ViewGroup)view);
        }
    }

    public static String mapToCsv(HashMap<String, String> m) throws IOException
    {
        StringBuilder stringBuilder = new StringBuilder();
        Iterator iter = m.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            stringBuilder.append(String.format("%s,%s%s", key, m.get(key), System.getProperty("line.separator")));
        }

        return stringBuilder.toString();
    }

}
