package kr.co.compcareworker.Util;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Patterns;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.kakao.sdk.navi.NaviClient;
import com.kakao.sdk.navi.model.CoordType;
import com.kakao.sdk.navi.model.Location;
import com.kakao.sdk.navi.model.NaviOption;
import com.kakao.sdk.navi.model.RpOption;
import com.kakao.sdk.navi.model.VehicleType;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import info.mqtt.android.service.MqttAndroidClient;
import kr.co.compcareworker.Data.ServiceList.FileAfter;
import kr.co.compcareworker.Data.ServiceList.FileBefore;
import kr.co.compcareworker.R;

public class Common {
    String TAG = "Common";
    String BASE_URL = "https://www.compcare.co.kr/";

    public ArrayList<FileBefore> currentServiceBeforeImage = new ArrayList<>();
    public ArrayList<FileAfter> currentServiceAfterImage = new ArrayList<>();
    SharedPreferences pref;

    private static Common ourInstance;

    public static Common getInstance() {
        if (ourInstance == null) {
            ourInstance = new Common();
        }
        return ourInstance;
    }

    // 값 넣기(String)
    public void setPref(Context context, String key, String value) {
        pref = context.getSharedPreferences(TAG, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(key, value);
        editor.commit();
    }

    // 값 불러오기(string)
    public String getPref(Context context, String key) {
        pref = context.getSharedPreferences(TAG, Activity.MODE_PRIVATE);
        if (pref.contains(key)) {
            return pref.getString(key, "");
        } else {
            return null;
        }
    }

    // 값 넣기(boolean)
    public void setPref(Context context, String key, boolean value) {
        pref = context.getSharedPreferences(TAG, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    // 값 불러오기(boolean)
    public boolean getPref(Context context, String key, boolean value) {
        pref = context.getSharedPreferences(TAG, Activity.MODE_PRIVATE);
        if (pref.contains(key)) {
//            Log.d("getPref(" + key + ")", "true");
            return true;
        } else {
//            Log.d("getPref(" + key + ")", "false");
            return false;
        }
    }

    // 값(Key Data) 삭제하기
    public void delPref(Context context, String key) {
        pref = context.getSharedPreferences(TAG, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.remove(key);
        editor.commit();
    }

    // 값(ALL Data) 삭제하기
    public void delAllPref(Context context) {
        pref = context.getSharedPreferences(TAG, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.clear();
        editor.commit();
    }

    public void getLocation(Context context, String name, String addr) {
        final Geocoder geocoder = new Geocoder(context);
        List<Address> list = null;

        double longitude = 0, latitude = 0;

        try {
            list = geocoder.getFromLocationName(
                    addr, // 지역 이름
                    10); // 읽을 개수
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (list != null) {
            if (list.size() != 0) {
                longitude = list.get(0).getLongitude();
                latitude = list.get(0).getLatitude();
            }
        }
        navigationDialog(context, name, longitude, latitude);

    }

    public void navigationDialog(Context context, final String des, final Double lon, final Double lat) {
        try {
            if (NaviClient.getInstance().isKakaoNaviInstalled(context)) {
//                //카카오 내비가 설치 되어 있다면 KakaoNaviParams 빌더를 통해 도착지 정보와 출발지 정보를 넘겨준다.
//                Location destination = Location.newBuilder(des, lon, lat).build();
//                NaviOption options = NaviOption.CREATOR.setCoordType(CoordType.WGS84).setVehicleType(VehicleType.FIRST).setRpOption(RpOption.SHORTEST).build();
//                KakaoNaviParams.Builder builder = KakaoNaviParams.newBuilder(destination).setNaviOptions(options);
//                //추가
//                KakaoNaviService.getInstance().shareDestination(context, builder.build());

                context.startActivity(
                        NaviClient.getInstance().navigateIntent(
                                new Location(des, lon.toString(), lat.toString()),
                                new NaviOption(CoordType.WGS84, VehicleType.FIRST, RpOption.SHORTEST)
                        )
                );
            } else {
                //카카오 내비가 설치되어 있지 않다면, 카카오 내비의 설치를 요청한다.
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                dialogBuilder.setMessage(context.getString(R.string.must_navi));
                dialogBuilder.setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_VIEW,
                                Uri.parse("https://play.google.com/store/apps/details?id=com.locnall.KimGiSa"));
                        context.startActivity(intent);
                        dialog.dismiss();
                    }
                }).setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, context.getString(R.string.navi_error), Toast.LENGTH_LONG).show();
        }
    }

//    public void navigationDialog(Context context, final String des, final Double lon, final Double lat) {
//        try {
//            TMapTapi tMapTapi = new TMapTapi(context);
//            //티맵 App Key 인증
//            tMapTapi.setSKTMapAuthentication("l7xx63ba437fe3cf4a069602ce6fc1312568");
//            //App Key 인증 리스너
//            if(MyApplication.tmap_succeed){
//
//                if(tMapTapi.isTmapApplicationInstalled()) {
//                    tMapTapi.invokeNavigate(des, Float.parseFloat(lon + ""), Float.parseFloat(lat + ""), 0, true);
//
//                } else {
//                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
//                    dialogBuilder.setMessage(context.getString(R.string.must_navi));
//                    dialogBuilder.setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            //확인 버튼을 누르면 플레이스토어 티맵 설치 페이지로 연결된다.
//                            dialog.dismiss();
//                            Intent intent = new Intent(Intent.ACTION_VIEW,
//                                    Uri.parse("https://play.google.com/store/apps/details?id=com.skt.tmap.ku&hl=ko&gl=US"));
//                            context.startActivity(intent);
//                        }
//                    }).setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                        }
//                    });
//                    dialogBuilder.show();
//                }
//            } else {
//
//                tMapTapi.setOnAuthenticationListener(new TMapTapi.OnAuthenticationListenerCallback() {
//                    @Override
//                    public void SKTMapApikeySucceed() {
//
//                        MyApplication.tmap_succeed = true;
//
//                        if (tMapTapi.isTmapApplicationInstalled()) {
//                            //티맵이 설치 되어 있다면 티맵을 연결한다. 목적지에 도착하면 티맵을 자동으로 종료한다.
//                            tMapTapi.invokeNavigate(des, Float.parseFloat(lon + ""), Float.parseFloat(lat + ""), 0, true);
//
//                        } else {
//                            //티맵이 설치 되어있지 않으면 팝업창을 띄워 설치를 요청한다.
//                            Handler handler = new Handler(Looper.getMainLooper());
//                            handler.postDelayed(new Runnable() {
//                                @Override
//                                public void run()
//                                {
//                                    // 토스트 창을 띄울 코드를 여기에 적어주자 : )
//                                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
//                                    dialogBuilder.setMessage(context.getString(R.string.must_navi));
//                                    dialogBuilder.setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() {
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int which) {
//                                            //확인 버튼을 누르면 플레이스토어 티맵 설치 페이지로 연결된다.
//                                            dialog.dismiss();
//                                            Intent intent = new Intent(Intent.ACTION_VIEW,
//                                                    Uri.parse("https://play.google.com/store/apps/details?id=com.skt.tmap.ku&hl=ko&gl=US"));
//                                            context.startActivity(intent);
//                                        }
//                                    }).setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int which) {
//                                            dialog.dismiss();
//                                        }
//                                    });
//                                    dialogBuilder.show();
//                                }
//                            }, 0);
//                        }
//                    }
//
//                    @Override
//                    public void SKTMapApikeyFailed(String s) {
//                        Handler handler = new Handler(Looper.getMainLooper());
//                        handler.postDelayed(new Runnable() {
//                            @Override
//                            public void run()
//                            {
//                                Toast.makeText(context, "티맵 실행에 실패하였습니다."+s, Toast.LENGTH_LONG).show();
//                            }
//                        }, 0);
//                    }
//                });
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            Toast.makeText(context, "티맵 실행에 실패하였습니다.", Toast.LENGTH_LONG).show();
//        }
//    }

    public Object isNull(Object s) {
        if (s == null) {
            return "";
        }

        return s;
    }

    public String isNullToZero(String s) {
        if (s == null) {
            return "0";
        }

        return s;
    }

    public int getWidth(Activity activity) {
        DisplayMetrics dm = activity.getApplicationContext().getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    public int getHeight(Activity activity) {
        DisplayMetrics dm = activity.getApplicationContext().getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    public int getDip(Context context, int dimen) {
        return (int) context.getResources().getDimension(dimen);
    }

    public String getBaseUrl(String mbid) {
        String baseUrl = BASE_URL;
        if (!TextUtils.isEmpty(mbid)) {
            baseUrl = String.format("https://%s.compcare.co.kr/", mbid);
        }

        return baseUrl;
    }

    public boolean isValidEmail(String email) {
        if (TextUtils.isEmpty(email)) {
            return false;
        } else {
            return Patterns.EMAIL_ADDRESS.matcher(email).matches();
        }
    }

    public void deleteDirectory(String dirPath) {
        File file = new File(dirPath);
        if (file.exists()) {
            File[] childFileList = file.listFiles();
            if (childFileList != null) {
                for (File childFile : childFileList) {
                    if (childFile != null && !childFile.isDirectory()) {
                        childFile.delete();
                    }
                }
            }
        }
    }

    public String moneyFormatToWon(int inputMoney) {
        DecimalFormat decimalFormat = new DecimalFormat("#,##0");
        return decimalFormat.format(inputMoney);
    }


    public String convert_mqtt_value_string(String name, String value) {
        String con = "";
        if (value != null && !value.equals("")) {
            con = "'" + name + "':'" + value + "'";
        }
        return con;
    }

    public String convert_mqtt_value_int(String name, Integer value) {
        String con = "";
        if (value != null && value > 0) {
            con = "'" + name + "': " + value;
        } else {
            con = "'" + name + "': -1";
        }
        return con;
    }

    public String convert_max(String name, String value) {
        String con = "";
        if (value != null && !value.equals("")) {
            con = "'" + name + "':'>" + name + "," + value + "'";
        }
        return con;
    }

    public String valueConvert(String value) {
        String ori_value = value;
        if (ori_value.contains(".")) {
            ori_value = ori_value.substring(0, ori_value.indexOf("."));
        }
        return ori_value;
    }

    public String valueConvert1(String value) {
        String ori_value = value;
        if (ori_value.contains(".")) {
            ori_value = ori_value.substring(0, ori_value.indexOf(".") + 2);
        } else {
            ori_value = ori_value + ".0";
        }
        return ori_value;
    }

    public String valueConvert2(String value) {
        String ori_value = value;
        if (ori_value.contains(".")) {
            ori_value = ori_value.substring(0, ori_value.indexOf(".") + 3);
        } else {
            ori_value = ori_value + ".00";
        }
        return ori_value;
    }


    public boolean isEllipsis(TextView textView) {
        // 1이 나온다는 것은 글씨가 줄여졌다는 것이다.
        if (textView.getLayout() != null) {
            return textView.getLayout().getEllipsisCount(textView.getLineCount() - 1) > 0;
        }
        return false;
    }

    public void setDirEmpty(Context context, String dirName) {
//        String path = Environment.getExternalStorageDirectory() + "/DCIM" + dirName;
        String dirPath = context.getExternalFilesDir(dirName).getAbsolutePath() + "/CompcareWorker";
        String path = Environment.getExternalStorageDirectory() + "/DCIM" + dirName;
        File dir = new File(path);
        File[] childFileList = dir.listFiles();
        if (dir.exists()) {
            for (File childFile : childFileList) {
                if (childFile.isDirectory()) {
                    setDirEmpty(context, childFile.getAbsolutePath());
                    //하위 디렉토리
                } else {
                    if (childFile.delete()) {
                        Log.d("fileDelete", childFile.getPath() + " <--- delete");
                    } else {
                        Log.d("fileDelete", childFile.getPath() + " <--- fail");
                    }
                }
            }

            if (dir.delete()) {
                Log.d("fileDelete", dir.getPath() + " <--- delete");
            } else {
                Log.d("fileDelete", dir.getPath() + " <--- fail");
            }
        }
    }


    public void condition_status(ImageView imageView, String data, String max_data, String chart_type, String up, String down) {

        float value = Float.parseFloat(data);
        float max_value = Float.parseFloat(max_data);
        float up_value = Float.parseFloat(up);
        float down_value = Float.parseFloat(down);

        //한계치 over >> 경고
        if (value > max_value || value < 0) {
            imageView.setImageResource(R.drawable.icon_red_square);

            //주의
        } else if (value > up_value || value < down_value) {
            imageView.setImageResource(R.drawable.icon_yellow_square);

            //정상
        } else {
            imageView.setImageResource(R.drawable.icon_green_square);
        }
    }


    public void condition_status_iot(Button button, String data, String max_data, String up, String down) {

        float value = Float.parseFloat(data);
        float max_value = Float.parseFloat(max_data);
        float up_value = Float.parseFloat(up);
        float down_value = Float.parseFloat(down);

        //한계치 over >> 경고
        if (value > max_value || value < 0) {
            button.setBackgroundResource(R.drawable.bg_red_round_opa40);

            //주의
        } else if (value > up_value || value < down_value) {
            button.setBackgroundResource(R.drawable.bg_yellow_round_opa40);

            //정상
        } else {
            button.setBackgroundResource(R.drawable.bg_green_round_opa40);
        }
    }

    public void toastShow(Context context, String message) {

        Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
        toast.show();

        Handler toast_hdr = new Handler();
        toast_hdr.postDelayed(new Runnable() {
            @Override
            public void run() {
                toast.cancel();
            }
        }, 1000);
    }

    public int getOrderOfWeek(int year, int month) {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DATE, 1);

        return calendar.get(Calendar.DAY_OF_WEEK);
    }

    public int getWeekOfMonth(int year, int month) {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
        return calendar.get(Calendar.WEEK_OF_MONTH);
    }

    public String getDateOfMonth(int year, int month, String type) throws ParseException {

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dataFormat;
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);

        int day;
        if (type.equals("first")) {
            calendar.set(Calendar.DATE, 1);
            dataFormat = new SimpleDateFormat("yyyyMMdd000000", Locale.KOREA);

        } else {
            day = calendar.getActualMaximum(Calendar.DATE);
            calendar.set(Calendar.DATE, day);
            dataFormat = new SimpleDateFormat("yyyyMMdd235959", Locale.KOREA);

        }
        Log.d("month type@@@@", dataFormat.format(calendar.getTime()));
        String new_time = dataFormat.format(calendar.getTime());

        SimpleDateFormat new_dataFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.KOREA);
        Date date = new_dataFormat.parse(new_time);

        return date.getTime() + "000000";
    }

    public String getDateOfWeek(int year, int month, int week, String type, boolean today) throws ParseException {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.WEEK_OF_MONTH, week);

        SimpleDateFormat dataFormat;

        if (type.equals("first")) {
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
            dataFormat = new SimpleDateFormat("yyyyMMdd000000", Locale.KOREA);

        } else {
            if (today) {
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE));
            } else {
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
            }
            dataFormat = new SimpleDateFormat("yyyyMMdd235959", Locale.KOREA);
        }

        Log.d("week type@@@@", dataFormat.format(calendar.getTime()));

        String new_time = dataFormat.format(calendar.getTime());
        SimpleDateFormat new_dataFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.KOREA);
        Date date = new_dataFormat.parse(new_time);

        return date.getTime() + "000000";
    }

    public String convert_time(String ori_date, boolean is_start) throws ParseException {

        if (is_start) {
            ori_date = ori_date + ".000000";
        } else {
            ori_date = ori_date + ".235959";
        }

        SimpleDateFormat new_dataFormat = new SimpleDateFormat("yyyy.MM.dd.HHmmss", Locale.KOREA);
        Date date = new_dataFormat.parse(ori_date);

        return date.getTime() + "000000";
    }

    public String convert_time2(String ori_date, boolean is_start) throws ParseException {

        if (is_start) {
            ori_date = ori_date + "0000";
        } else {
            ori_date = ori_date + "5959";
        }

        SimpleDateFormat new_dataFormat = new SimpleDateFormat("yyyy.MM.dd.HHmmss", Locale.KOREA);
        Date date = new_dataFormat.parse(ori_date);

        return date.getTime() + "000000";
    }

    public int get_horsepower_output(String mc_horsepower) {
        int output = 0;

        switch (mc_horsepower) {
            case "20HP":
                output = 15;
                break;
            case "30HP":
                output = 22;
                break;
            case "50HP":
                output = 37;
                break;
            case "75HP":
                output = 55;
                break;
            case "100HP":
                output = 75;
                break;
            case "150HP":
                output = 110;
                break;
            case "200HP":
                output = 160;
                break;
        }

        return output;
    }
}
