package ugen.fy.plugin;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.oauth.OauthPlateform;
import com.alibaba.sdk.android.openaccount.OauthService;
import com.alibaba.sdk.android.openaccount.OpenAccountSDK;
import com.alibaba.sdk.android.openaccount.callback.LoginCallback;
import com.alibaba.sdk.android.openaccount.model.OpenAccountSession;
import com.alibaba.sdk.android.openaccount.ui.OpenAccountUIConfigs;
import com.alibaba.sdk.android.openaccount.ui.OpenAccountUIService;
import com.alibaba.sdk.android.openaccount.ui.callback.EmailRegisterCallback;
import com.alibaba.sdk.android.openaccount.ui.callback.EmailResetPasswordCallback;
import com.alibaba.sdk.android.openaccount.ui.impl.OpenAccountUIServiceImpl;
import com.alibaba.sdk.android.openaccount.ui.ui.LoginActivity;
import com.alibaba.sdk.android.openaccount.util.ResourceUtils;
import com.aliyun.iot.aep.oa.OALanguageUtils;
import com.aliyun.iot.aep.sdk.IoTSmart;
import com.aliyun.iot.aep.sdk.log.ALog;
import com.aliyun.iot.aep.sdk.login.ILoginCallback;
import com.aliyun.iot.aep.sdk.login.LoginBusiness;
// import com.aliyun.iot.ilop.demo.page.debug.EnvironmentActivity;
import com.aliyun.iot.ilop.startpage.list.main.countryselect.CountryListActivity;
import com.aliyun.iot.ilop.startpage.list.main.utils.LocateHandler.OnLocationListener;
import com.aliyun.iot.ilop.startpage.list.main.utils.LocateTask;
import com.aliyun.iot.ilop.startpage.list.main.utils.LocationUtil;
import com.aliyun.iot.link.ui.component.LinkToast;
import ugen.fy.plugin.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class OALoginActivity extends LoginActivity implements View.OnClickListener, AuthCodeFragment.Listener, OnLocationListener {

    private static final boolean supportMobile = false;

    private ArrayList<IoTSmart.Country> mCountries = new ArrayList<>();
    private IoTSmart.Country mSelectedCountry;
    private static final int ACCESS_COARSE_LOCATION1 = 1;
    private LocateTask locateTask;

    private RegisterSelectorDialogFragment registerSelectorDialogFragment;
    private ResetSelectorDialogFragment resetSelectorDialogFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //显示登录页和手机忘记密码页的选择国家区号
        OpenAccountUIConfigs.AccountPasswordLoginFlow.supportForeignMobileNumbers = supportMobile;
        OpenAccountUIConfigs.MobileResetPasswordLoginFlow.supportForeignMobileNumbers = supportMobile;
        super.onCreate(savedInstanceState);
        TRANSPARENT();
//        mToolBar.setLogo(R.drawable.back_arrow);
        // findViewById(R.id.btn_gmail).setOnClickListener(this);
//        findViewById(R.id.btn_facebook).setOnClickListener(this);


        registerSelectorDialogFragment = new RegisterSelectorDialogFragment();
        registerSelectorDialogFragment.setOnClickListener(registerListenr);

        resetSelectorDialogFragment = new ResetSelectorDialogFragment();
        resetSelectorDialogFragment.setOnClickListener(resetListenr);


        this.resetPasswordTV = this.findViewById(ResourceUtils.getRId(this, "reset_password"));
        if (this.resetPasswordTV != null) {
            this.resetPasswordTV.setOnClickListener(v -> {
                if (supportMobile) {
                    resetSelectorDialogFragment.showAllowingStateLoss(getSupportFragmentManager(), "");
                } else {
                    forgetMailPassword(v);
                }
            });
        }
        this.registerTV = this.findViewById(ResourceUtils.getRId(this, "register"));
        if (this.registerTV != null) {
            this.registerTV.setOnClickListener(v -> {
                if (supportMobile) {
                    registerSelectorDialogFragment.showAllowingStateLoss(getSupportFragmentManager(), "");
                } else {
                    OpenAccountUIService openAccountUIService = OpenAccountSDK.getService(OpenAccountUIService.class);
                    openAccountUIService.showEmailRegister(OALoginActivity.this, getEmailRegisterCallback());
                }
            });
        }

        // findViewById(R.id.switch_env).setOnClickListener(view -> EnvironmentActivity.show(view.getContext()));

        // findViewById(R.id.switch_env).setOnLongClickListener(view -> false);

        // findViewById(R.id.authcode_login).setOnClickListener(new View.OnClickListener() {
        //     @Override
        //     public void onClick(View view) {
        //         new AuthCodeFragment().show(getSupportFragmentManager(), "1576063472");
        //     }
        // });

        mSelectedCountry = IoTSmart.getCountry();

        if (mSelectedCountry == null) {
// {
//     "areaName": "中国大陆",
//     "code": "86",
//     "domainAbbreviation": "CN",
//     "isoCode": "CHN",
//     "pinyin": "ZhongGuoDaLu"
// }
// {
//     "areaName": "美国",
//     "code": "1",
//     "domainAbbreviation": "US",
//     "isoCode": "USA",
//     "pinyin": "MeiGuo"
// }
            mSelectedCountry = new IoTSmart.Country();
            mSelectedCountry.areaName = "德国"; // 为防止哪天美国佬又发疯搞服务器限制，还是默认定位在德国以便使用阿里生活物联网平台的德国服务器吧
            mSelectedCountry.code = "49";
            mSelectedCountry.domainAbbreviation = "DE";
            mSelectedCountry.isoCode = "DEU";
            mSelectedCountry.pinyin = "DeGuo";
            IoTSmart.setCountry(mSelectedCountry, new IoTSmart.ICountrySetCallBack() {
                @Override
                public void onCountrySet(boolean needRestartApp) {
                    if (needRestartApp) {
                        ALog.d(AliLiving.TAG, mSelectedCountry.areaName + " CountrySet default needRestartApp");
                    } else {
                        ALog.d(AliLiving.TAG, mSelectedCountry.areaName + " CountrySet default");
                    }
                }
            });
        }

        //如果没有权限请求权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(OALoginActivity.this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                ACCESS_COARSE_LOCATION1);
        }
        //判断定位服务是否打开
        if (!LocationUtil.isLocationEnabled(this)) {
            LocationUtil.remindStartLocateService(this);
        }

        IoTSmart.getCountryList(new IoTSmart.ICountryListGetCallBack() {
            @Override
            public void onSucess(List<IoTSmart.Country> countryList) {
                if (countryList != null) {
                    // String veryLongString = JSON.toJSONString(countryList);
                    // int maxLogSize = 600;
                    // for (int i = 0; i <= veryLongString.length() / maxLogSize; i++) {
                    //     int start = i * maxLogSize;
                    //     int end = (i + 1) * maxLogSize;
                    //     end = end > veryLongString.length() ? veryLongString.length() : end;
                    //     ALog.d(AliLiving.TAG, veryLongString.substring(start, end));
                    // }
                    onCountryListLoaded(countryList);
                } else {
                    // ALog.d(AliLiving.TAG, "load country list failed");
                    // Toast.makeText(CountryListActivity.this, "Failed to load list data from remote", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFail(String s, int i, String s1) {
                // ALog.d(AliLiving.TAG, "load country list failed");
                // Toast.makeText(CountryListActivity.this, s1, Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public void onClick(View v) {
        Intent intent = new Intent(OALoginActivity.this, CountryListActivity.class);
        intent.putExtra("type", "oauto_google");
        startActivityForResult(intent, 200);

       /* OauthService oauthService = OpenAccountSDK.getService(OauthService.class);
        int oaCode = OauthPlateform.GOOGLE;
        if (v.getId() == R.id.btn_gmail) {
            oaCode = OauthPlateform.GOOGLE;
            //            case R.id.btn_facebook:
//                oaCode = OauthPlateform.FACEBOOK;
//                break;
        }
        try {
            oauthService.oauth(this, oaCode, new LoginCallback() {
                @Override
                public void onSuccess(OpenAccountSession session) {
                    LoginCallback loginCallback = OALoginActivity.this.getLoginCallback();
                    if (loginCallback != null) {
                        loginCallback.onSuccess(session);
                    }
                    OALoginActivity.this.finishWithoutCallback();
                }

                @Override
                public void onFailure(int code, String msg) {
                    Log.e(AliLiving.TAG, "onFailure: " + msg);
                    Toast.makeText(OALoginActivity.this, "oauth 失败 code = " + code + " message = " + msg, Toast.LENGTH_LONG).show();

                    LoginCallback loginCallback = OALoginActivity.this.getLoginCallback();
                    if (loginCallback != null) {
                        loginCallback.onFailure(code, msg);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }


    private void setOautoLogin(int oaCode) {
        try {
            OauthService oauthService = OpenAccountSDK.getService(OauthService.class);
            oauthService.oauth(this, oaCode, new LoginCallback() {
                @Override
                public void onSuccess(OpenAccountSession session) {
                    LoginCallback loginCallback = OALoginActivity.this.getLoginCallback();
                    if (loginCallback != null) {
                        loginCallback.onSuccess(session);
                    }
                    OALoginActivity.this.finishWithoutCallback();
                }

                @Override
                public void onFailure(int code, String msg) {
                    Log.e(AliLiving.TAG, "onFailure: " + msg);
                    Toast.makeText(OALoginActivity.this, "oauth 失败 code = " + code + " message = " + msg, Toast.LENGTH_LONG).show();

                    LoginCallback loginCallback = OALoginActivity.this.getLoginCallback();
                    if (loginCallback != null) {
                        loginCallback.onFailure(code, msg);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private View.OnClickListener registerListenr = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(OALoginActivity.this, CountryListActivity.class);


            if (v.getId() == R.id.btn_register_phone) {//手机注册
                intent.putExtra("type", "phone");
            } else if (v.getId() == R.id.btn_register_email) {//邮箱注册
                intent.putExtra("type", "mail");
            }
            startActivity(intent);
            overridePendingTransition(0, 0);
            registerSelectorDialogFragment.dismissAllowingStateLoss();
        }
    };


    private View.OnClickListener resetListenr = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btn_register_phone) {//手机找回
                forgetPhonePassword(v);
                resetSelectorDialogFragment.dismissAllowingStateLoss();
            } else if (v.getId() == R.id.btn_register_email) {//邮箱找回
                forgetMailPassword(v);
                resetSelectorDialogFragment.dismissAllowingStateLoss();
            }
        }
    };

    public void forgetPhonePassword(View view) {
        super.forgetPassword(view);
    }

    public void forgetMailPassword(View view) {
        OpenAccountUIService openAccountUIService = (OpenAccountUIService) OpenAccountSDK.getService(OpenAccountUIService.class);
        openAccountUIService.showEmailResetPassword(this, this.getEmailResetPasswordCallback());
    }

    private EmailResetPasswordCallback getEmailResetPasswordCallback() {
        return new EmailResetPasswordCallback() {

            @Override
            public void onSuccess(OpenAccountSession session) {
                LoginCallback callback = getLoginCallback();
                if (callback != null) {
                    callback.onSuccess(session);

                }
                finishWithoutCallback();
            }

            @Override
            public void onFailure(int code, String message) {
                LoginCallback callback = getLoginCallback();
                if (callback != null) {
                    callback.onFailure(code, message);
                }
            }

            @Override
            public void onEmailSent(String email) {
                Toast.makeText(getApplicationContext(), email + " 已经发送了", Toast.LENGTH_LONG).show();
            }

        };
    }

    private EmailRegisterCallback getEmailRegisterCallback() {
        return new EmailRegisterCallback() {

            @Override
            public void onSuccess(OpenAccountSession session) {
                LoginCallback callback = getLoginCallback();
                if (callback != null) {
                    callback.onSuccess(session);
                }
                finishWithoutCallback();
            }

            @Override
            public void onFailure(int code, String message) {
                LoginCallback callback = getLoginCallback();
                if (callback != null) {
                    callback.onFailure(code, message);
                }
            }

            @Override
            public void onEmailSent(String email) {
                Toast.makeText(getApplicationContext(), email + " 已经发送了", Toast.LENGTH_LONG).show();
            }

        };
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 200 && resultCode == 201) {
            String code = data.getStringExtra("accountCode");
            LoginBusiness.authCodeLogin(code, new ILoginCallback() {
                @Override
                public void onLoginSuccess() {
                    finish();
                    overridePendingTransition(0, 0);
                }

                @Override
                public void onLoginFailed(int i, String s) {
                    ALog.d(AliLiving.TAG, "code->" + i + ", str->" + s);
                    LinkToast.makeText(OALoginActivity.this, s).show();
                }
            });
        } else if (requestCode == 200 && resultCode == 202) {
            setOautoLogin(OauthPlateform.GOOGLE);
        } else {
            OauthService service = OpenAccountSDK.getService(OauthService.class);
            if (service != null) {
                service.authorizeCallback(requestCode, resultCode, data);
            }
        }
    }


    protected final void TRANSPARENT() {
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(OALanguageUtils.attachBaseContext(newBase));
    }

    @Override
    protected String getLayoutName() {
        return supportMobile ? "ali_sdk_openaccount_login2" : "ali_sdk_openaccount_login_email";
    }

    @SuppressWarnings("unused")
    static class CountryExt {
        private static boolean isChina() {
            try {
                return IoTSmart.getLanguage().equalsIgnoreCase("zh-CN");
            } catch (Exception ignored) {
                return false;
            }
        }

        static String getNameSort(@NonNull IoTSmart.Country country) {
            try {
                if (isChina()) {
                    return country.pinyin.substring(0, 1);
                } else {
                    return country.areaName.substring(0, 1);
                }
            } catch (NullPointerException | IndexOutOfBoundsException ignored) {
                return "";
            }
        }

        static String getComparatorFiled(@NonNull IoTSmart.Country country) {
            try {
                if (isChina()) {
                    return country.pinyin;
                } else {
                    return country.areaName;
                }
            } catch (NullPointerException ignored) {
                return "";
            }
        }
    }

    private void onCountryListLoaded(List<IoTSmart.Country> countryList) {
        if (isDestroyed() || isFinishing()) return;
        if (null == countryList) {
            return;
        }
        mCountries.clear();
        mCountries.addAll(countryList);
        Collections.sort(mCountries, (o1, o2) -> CountryExt.getComparatorFiled(o1).compareTo(CountryExt.getComparatorFiled(o2)));

        startLocation();
    }

    private void startLocation() {
        //首先请求一次定位服务
        LocationUtil.requestLocation(this);
        if (mCountries != null) {
            locateTask = new LocateTask(this, mCountries, this);
            locateTask.startLocation();
        }
    }

    @Override
    public void onSuccessLocate(final IoTSmart.Country country) {
        // mSelectedCountry = country;

        mSelectedCountry = new IoTSmart.Country();
        mSelectedCountry.areaName = "德国"; // 为防止哪天美国佬又发疯搞服务器限制，还是默认定位在德国以便使用阿里生活物联网平台的德国服务器吧
        mSelectedCountry.code = "49";
        mSelectedCountry.domainAbbreviation = "DE";
        mSelectedCountry.isoCode = "DEU";
        mSelectedCountry.pinyin = "DeGuo";

        IoTSmart.setCountry(mSelectedCountry, new IoTSmart.ICountrySetCallBack() {
            @Override
            public void onCountrySet(boolean needRestartApp) {
                if (needRestartApp) {
                    ALog.d(AliLiving.TAG, mSelectedCountry.areaName + " CountrySet located needRestartApp");
                } else {
                    ALog.d(AliLiving.TAG, mSelectedCountry.areaName + " CountrySet located");
                }
            }
        });
    }

    @Override
    public void onContinuedLocate(String text) {}

    @Override
    public void onFailLocate() {}

    @Override
    public void onAuthCodeClicked(int position) {
        try {
            Intent intent = new Intent(OALoginActivity.this, CountryListActivity.class);
            intent.putExtra("type", "auto");
            intent.putExtra("accountCode", AuthCodeFragment.STATIC_AUTH_CODES[position]);
            startActivityForResult(intent, 200);
        } catch (IndexOutOfBoundsException ignored) {

        }
    }

    @Override
    protected LoginCallback getLoginCallback() {
        if (super.getLoginCallback() == null) {
            OpenAccountUIServiceImpl._loginCallback = new LoginCallback() {
                @Override
                public void onFailure(int i, String s) {

                }

                @Override
                public void onSuccess(OpenAccountSession openAccountSession) {
                    overridePendingTransition(0, 0);
                }
            };
            return OpenAccountUIServiceImpl._loginCallback;
        }
        return super.getLoginCallback();
    }
}
