package kr.co.hanwha.hifive.admin;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.view.View;
import android.widget.Button;

import com.google.firebase.iid.FirebaseInstanceId;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import kr.co.hanwha.hifive.HFApplication;
import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.base.BaseActivity;
import kr.co.hanwha.hifive.data.model.AlarmData;
import kr.co.hanwha.hifive.data.source.MemberDataRepository;
import kr.co.hanwha.hifive.dialog.HFSingleDialog;
import kr.co.hanwha.hifive.enums.BaseAnimationType;
import kr.co.hanwha.hifive.enums.BaseToolbarType;
import kr.co.hanwha.hifive.network.HFNetworkUtil;
import kr.co.hanwha.hifive.screen.intro.IntroActivity;
import kr.co.hanwha.hifive.util.HFActivityUtil;
import kr.co.hanwha.hifive.util.HFCommonUtil;

/**
 * Created by sanghoonkwon on 2018. 2. 13..
 */

public class TestModeActivity extends BaseActivity {
    private Button btnServer = null;
    private Button btnLog = null;

    @Override
    protected int getContentViewResource() {
        return R.layout.activity_test_mode;
    }

    @Override
    protected BaseToolbarType isToolbarStyle() {
        return BaseToolbarType.ONLY_CLOSE;
    }


    @Override
    protected BaseAnimationType isShowActivityAnimation() {
        return BaseAnimationType.BOTTOM;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Button btnReset = (Button) findViewById(R.id.btnReset);
        Button btnPushTest = (Button) findViewById(R.id.btnPushTest);
        Button btnDeviceInfo = (Button) findViewById(R.id.btnDeviceInfo);
        Button btnWebview = (Button) findViewById(R.id.btnWebview);
        btnServer = (Button) findViewById(R.id.btnServer);
        String server = "SERVER";
        if (HFApplication.SERVER == HFApplication.SERVER_TYPE.REAL) server = "SERVER(REAL)";
        else if (HFApplication.SERVER == HFApplication.SERVER_TYPE.DEV) server = "SERVER(DEV)";
        else if (HFApplication.SERVER == HFApplication.SERVER_TYPE.LOCAL) server = "SERVER(LOCAL)";

        btnServer.setText(server);

        btnLog = (Button) findViewById(R.id.btnLog);
        btnLog.setText("LOG : " + (HFApplication.DEV_LOG ? "ON" : "OFF"));

        btnReset.setOnClickListener(onClickListener);
        btnPushTest.setOnClickListener(onClickListener);
        btnDeviceInfo.setOnClickListener(onClickListener);
        btnWebview.setOnClickListener(onClickListener);
        btnServer.setOnClickListener(onClickListener);
        btnLog.setOnClickListener(onClickListener);
    }

    /**************************************************
     * 				View.OnClickListener
     **************************************************/
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btnReset:
                    restart();
                    break;
                case R.id.btnPushTest:
                    pushTest();
                    break;
                case R.id.btnDeviceInfo: {
                    String keyHash = "";
                    try {
                        PackageInfo info = getPackageManager().getPackageInfo("kr.co.hanwha.hifive", PackageManager.GET_SIGNATURES);
                        for (Signature signature : info.signatures) {
                            MessageDigest md = MessageDigest.getInstance("SHA");
                            md.update(signature.toByteArray());
                            keyHash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
                        }
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    }

                    String info = "Device Id : " + HFCommonUtil.getDeviceUUID(TestModeActivity.this);
                    info += "\nMEMBER ID : " + MemberDataRepository.getInstance().getLoginData().getMember_id();
                    info += "\nMEMBER ID(ENC) : " + MemberDataRepository.getInstance().getLoginData().getEncryption_member_id();
                    info += "\nApp Version : " + HFCommonUtil.getAppVersion(TestModeActivity.this);
                    info += "\nOS Version : " + HFCommonUtil.getDeviceOsVersion();
                    info += "\nMODEL : " + HFCommonUtil.getDeviceModelName();
                    info += "\nTOKEN : " + FirebaseInstanceId.getInstance().getToken();
                    info += "\nkeyHash : " + keyHash;
                    showDeviceInfo(info);
                    break;
                }
                case R.id.btnWebview: {
                    HFNetworkUtil networkUtil = new HFNetworkUtil();
                    AdminInputDialog dialog = new AdminInputDialog(TestModeActivity.this,
                            AdminInputDialog.ADMIN_TYPE.URL,
                            networkUtil.getTestUrl(),
                            new AdminInputDialog.OnDialogCallback() {
                                @Override
                                public void onPositive(@NonNull String message) {
                                    try {
                                        String encryption = MemberDataRepository.getInstance().getEncryptionMemberId();
                                        HFActivityUtil.startCommonWebViewActivity(TestModeActivity.this, message, encryption);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onWrongPassword() {

                                }
                            });
                    dialog.show();
                    break;
                }
                case R.id.btnServer: {
                    new TestModeDialog(TestModeActivity.this, new TestModeDialog.OnDialogCallback() {
                        @Override
                        public void onConfirm() {
                            startActivity(new Intent(TestModeActivity.this, IntroActivity.class));
                            finish();
                        }
                    }).show();
                    break;
                }
                case R.id.btnLog: {
                    HFApplication.DEV_LOG = !HFApplication.DEV_LOG;
                    btnLog.setText("LOG : " + (HFApplication.DEV_LOG ? "ON" : "OFF"));
                    break;
                }
            }
        }
    };

    private void showDeviceInfo(final String deviceInfo) {
        showAlert("Device Info", deviceInfo, new HFSingleDialog.OnDialogCallback() {
            @Override
            public void onPositive() {
                HFCommonUtil.copyClipboard(TestModeActivity.this, deviceInfo, "클립보드에 복사되었습니다.");
            }
        });
    }

    private void restart() {
        HFActivityUtil.startIntroActivity(this);
        finish();
    }

    /**************************************************
     * 					Notification
     **************************************************/
    private void pushTest() {
        AlarmData data = new AlarmData();
        data.setTitle("알림 테스트");
        data.setMessage("푸쉬 테스트 중입니다");
        data.setCreated_at("2017-10-20 23:59:59.0");
        makeNotification(data);
    }

    /**************************************************
     * 					Notification
     **************************************************/
    AlarmData mAlarmData;

    private void makeNotification(AlarmData data) {
        this.mAlarmData = data;
        new AcyncTaskNotification().execute();
    }

    private class AcyncTaskNotification extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            makeNotification();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);


            /*
            showAlert("알림", mAlarmData.getMessage(), new GWDefaultDialog.OnDialogCallback() {
                @Override
                public void onNegative() {

                }

                @Override
                public void onPositive() {

                }
            });
            */
        }
    }

    private void makeNotification() {
        try {
            /*
            Intent intent = new Intent(getApplicationContext(), IntroActivity.class);
            intent.putExtra(GWNotiUtil.KEY_TYPE, "20");
            intent.putExtra(GWNotiUtil.KEY_VALUE1, "50");
            intent.putExtra(GWNotiUtil.KEY_VALUE2, "32");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);

            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            if (mAlarmData != null) {
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
                mBuilder.setSmallIcon(R.drawable.noti_icon);    //required
//                mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.iconlogo));
                mBuilder.setContentTitle(mAlarmData.getTitle());                //required
                mBuilder.setContentText(mAlarmData.getMessage());               //required
                mBuilder.setStyle(new android.support.v4.app.NotificationCompat.BigTextStyle());
                mBuilder.setTicker(mAlarmData.getMessage());                    //optional
                mBuilder.setAutoCancel(true);
                mBuilder.setContentIntent(pendingIntent);

                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
            }
            */

        } catch (Exception e) {
            /*
            String group_id = "1";
            String type = "20";
            String value1 = "50";
            String value2 = "32";
            String title = "test";
            String message = "message";

            Intent intent = new Intent(getApplicationContext(), IntroActivity.class);
            if (TextUtils.isEmpty(group_id) == false)
                intent.putExtra(HFNotiUtil.KEY_GROUP_ID, group_id);
            if (TextUtils.isEmpty(type) == false) intent.putExtra(HFNotiUtil.KEY_TYPE, type);
            if (TextUtils.isEmpty(value1) == false) intent.putExtra(HFNotiUtil.KEY_VALUE1, value1);
            if (TextUtils.isEmpty(value2) == false) intent.putExtra(HFNotiUtil.KEY_VALUE2, value2);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);

            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
            mBuilder.setSmallIcon(R.mipmap.noti_icon);    // required
            //mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.iconlogo));
            mBuilder.setContentTitle(title);                // required
            mBuilder.setContentText(message);               // required
            mBuilder.setStyle(new android.support.v4.app.NotificationCompat.BigTextStyle());
            mBuilder.setTicker(message);                    // optional
            mBuilder.setAutoCancel(true);
            mBuilder.setContentIntent(pendingIntent);
//                mBuilder.setSound(Uri.parse("android.resource://co.kr.hanwha.NGW/" + R.raw.notification));


            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
            */
            e.printStackTrace();
        }
    }
}
