package com.tomastc.smartwatchclient.lib.common;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;

import com.tomastc.smartwatchclient.R;
import com.tomastc.smartwatchclient.lib.Settings;
import com.tomastc.smartwatchclient.lib.SimpleSpinObject;
import com.tomastc.smartwatchclient.lib.SpinAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;

public class Utils {

    public static void playMedia(Context context, int media) {
        MediaPlayer mediaPlayer = MediaPlayer.create(context, media);
        mediaPlayer.start();
    }
    public static void setBackground(Context context, RelativeLayout layout) {
        try {
            // Check internal storage file exist or not
            Bitmap bmp = null;
            if (Settings.getBackground() != null) {
                bmp = Settings.getBackground();
            } else if (Settings.getMgmtList().containsKey("background-file")) {
                // try read from image directly
                String filename = Settings.getMgmtList().get("background-file");
                File file = new File(context.getFilesDir().getAbsolutePath() + "/" +
                        filename);
                if (file.exists()) {

                    // Load bitmap from file
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                    bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
                }
            }

            if (bmp != null) {
                Drawable dr = new BitmapDrawable(bmp);
                layout.setBackgroundDrawable(dr);
            }

        } catch (Exception e) {
            Log.e(context.getString(R.string.tag), e.getMessage());
        }
    }

    public static Bitmap getBitmapFromURL(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    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 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();
    }

    public static long[] VIBRATE_PATTERN1 = { 0, 500, 50, 100, 50, 100 };
    public static long[] VIBRATE_PATTERN2 = { 0, 100, 50, 100, 50 };
    public static void vibrate(Context context, long[] millisecs) {
        Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(millisecs, -1);
    }

    public static void playSound(Context context) throws IllegalArgumentException,
            SecurityException,
            IllegalStateException,
            IOException {

        Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

        if(alert == null){
            // alert is null, using backup
            alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            // I can't see this ever being null (as always have a default notification)
            // but just incase
            if(alert == null) {
                // alert backup is null, using 2nd backup
                alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            }
        }

        if (alert == null) {
            return;
        }


        MediaPlayer mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(context, alert);
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

        if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            // Uncomment the following line if you aim to play it repeatedly
            // mMediaPlayer.setLooping(true);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        }
    }

}
