package com.uas.module.home.main;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.just.agentweb.AgentWeb;
import com.uas.module.home.R;
import com.uas.module.home.network.grpc.Authentication;
import com.uas.module.home.network.grpc.MobileClientAuthenticationInterceptor;
import com.usoftchina.uu.mobile.grpc.api.AccountInfo;
import com.usoftchina.uu.mobile.grpc.api.AccountServiceGrpc;
import com.usoftchina.uu.mobile.grpc.api.AccountSigninRequest;
import com.usoftchina.uu.mobile.grpc.api.AccountSigninResponse;
import com.usoftchina.uu.mobile.grpc.api.AccountSignoutRequest;
import com.usoftchina.uu.mobile.grpc.api.AccountSignoutResponse;
import com.usoftchina.uu.mobile.grpc.api.AccountSignupRequest;
import com.usoftchina.uu.mobile.grpc.api.AccountSignupResponse;
import com.usoftchina.uu.mobile.grpc.api.AppServiceGrpc;
import com.usoftchina.uu.mobile.grpc.api.AuthedToken;
import com.usoftchina.uu.mobile.grpc.api.DeviceInfo;
import com.usoftchina.uu.mobile.grpc.api.GetAppConfigRequest;
import com.usoftchina.uu.mobile.grpc.api.GetAppConfigResponse;
import com.usoftchina.uu.mobile.grpc.api.GetHomeConfigRequest;
import com.usoftchina.uu.mobile.grpc.api.GetHomeConfigResponse;
import com.usoftchina.uu.mobile.grpc.api.GetMessageConfigRequest;
import com.usoftchina.uu.mobile.grpc.api.GetMessageConfigResponse;
import com.usoftchina.uu.mobile.grpc.api.HomeServiceGrpc;
import com.usoftchina.uu.mobile.grpc.api.MessageServiceGrpc;
import com.usoftchina.uu.mobile.grpc.api.ResponseHeader;
import com.usoftchina.uu.mobile.grpc.api.SwitchCompanyRequest;
import com.usoftchina.uu.mobile.grpc.api.SwitchCompanyResponse;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;


@Route(path = "/home/test")
public class TestMainActivity extends AppCompatActivity {
    
    //10.1.81.83
    ManagedChannel channel = ManagedChannelBuilder.forAddress("uu-api-test.usoftchina.com", 9620)
            .intercept(new MobileClientAuthenticationInterceptor())
            .usePlaintext(true)
            .build();

    AgentWeb  mAgentWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_main);


        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent((ViewGroup) this.findViewById(R.id.container),new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go("http://www.jd.com")
                .clearWebCache();
        
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                //注册
//                signup();
//
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                //登录
//                login();
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                //切换公司
//                switchCompany();
//                
//                //读取配置
//                getConfig();
//                //应用配置
//                getAppConfig();
//                //我的配置
//                getMeConfig();
//            }
//        }).start();
        
    }


    /*注册*/
    public  void signup() {
        LogUtils.d("----开始注册---------");
        //uu-api-test.usoftchina.com
        AccountSignupRequest request = AccountSignupRequest.newBuilder()
                .setMobile("15018524229")
                .setEmail("liuj@usoftchina.com")
                .setRealname("刘杰")
                .setSex(AccountInfo.Sex.MALE)
                .setPassword("111111")
                .build();
        try {
       
            AccountSignupResponse response = AccountServiceGrpc.newBlockingStub(channel).signup(request);
            ResponseHeader header = response.getResponseHeader();
            
            if (header.getSuccess()) {
                LogUtils.d("header:"+header.getMessage());
            } else {
                LogUtils.d("header:"+header.getCode() + "," + header.getMessage());
       
            }
        } catch (StatusRuntimeException e) {
            LogUtils.d("header Exception:"+e.getStatus().getCode() + "," + e.getStatus().getDescription());
           
        }
        
    }
    
    /*登录*/
    public void login(){
        LogUtils.d("-----开始登录--------");
        try {
            AccountSigninResponse response = AccountServiceGrpc.newBlockingStub(channel).signin(AccountSigninRequest.newBuilder()
                    .setMobile("15018524229")
                    .setPassword("111111")
                    .setDeviceInfo(DeviceInfo.newBuilder()
                            .setOs(DeviceInfo.OS.ANDROID))
                    .build());
            ResponseHeader header = response.getResponseHeader();
            if (header.getSuccess()) {
                System.out.println(response.getAccount());


                AuthedToken token = response.getAuthedToken();
                
                LogUtils.d("login token:"+token.getToken());
                LogUtils.d("account:"+JSON.toJSONString(response.getAccount()));
                // 登录成功后记录auth信息
                Authentication.set(token.getToken());

                if (response.getActiveCompanyId() > 0) {
                    System.out.println("current selected company " + response.getActiveCompanyId());
                } else if (response.getCompanyCount() > 0) {
                    LogUtils.d("公司账套："+JSON.toJSONString(response.getCompanyList()));
                }
                if (response.getMessageConfigCount() > 0) {
                    LogUtils.d("消息配置："+JSON.toJSONString(response.getMessageConfigList()));
                }
                if (response.getAppGroupConfigCount() > 0) {
                    LogUtils.d("应用组配置："+JSON.toJSONString(response.getAppGroupConfigList()));
                }
                if (response.getHomeConfigCount() > 0) {
                    LogUtils.d("我的配置："+JSON.toJSONString(response.getHomeConfigList()));
                }
                if (response.getUnreadMessageCountCount() > 0) {
                    LogUtils.d("未读消息："+JSON.toJSONString(response.getUnreadMessageCountList()));
                }
            } else {
                // error return by ResponseHeader
                System.err.println(header.getCode() + "," + header.getMessage());
            }
        } catch (StatusRuntimeException e) {
            // error return by Exception
            System.err.println(e.getStatus().getCode() + "," + e.getStatus().getDescription());
        }
    }


    /*切换公司-会产生新的Token*/
    public void switchCompany() {
        SwitchCompanyRequest request = SwitchCompanyRequest.newBuilder()
                .setCompanyId(10050540).build();
        try {
            SwitchCompanyResponse response = AccountServiceGrpc.newBlockingStub(channel).switchCompany(request);
            ResponseHeader header = response.getResponseHeader();
            if (header.getSuccess()) {
                // new authentication
                AuthedToken token = response.getAuthedToken();
                LogUtils.d("login token:"+token.getToken());
                // 登录成功后记录auth信息
                Authentication.set(token.getToken());
                LogUtils.d(""+response.getAuthedToken());
            } else {
                // error return by ResponseHeader
                System.err.println(header.getCode() + "," + header.getMessage());
            }
        } catch (StatusRuntimeException e) {
            // error return by Exception
            System.err.println(e.getStatus().getCode() + "," + e.getStatus().getDescription());
        }
    }



    /*退出*/
    public void signout() {
        AccountSignoutRequest request = AccountSignoutRequest.newBuilder().build();
        try {
            AccountSignoutResponse response = AccountServiceGrpc.newBlockingStub(channel).signout(request);
            ResponseHeader header = response.getResponseHeader();
            if (header.getSuccess()) {
                System.out.println("success");
            } else {
                // error return by ResponseHeader
                System.err.println(header.getCode() + "," + header.getMessage());
            }
        } catch (StatusRuntimeException e) {
            // error return by Exception
            System.err.println(e.getStatus().getCode() + "," + e.getStatus().getDescription());
        }
    }
    
    
    
    
    /*消息配置*/

    public void getConfig() {
        GetMessageConfigRequest request = GetMessageConfigRequest.newBuilder().build();
        try {
            GetMessageConfigResponse response = MessageServiceGrpc.newBlockingStub(channel).getConfig(request);
            ResponseHeader header = response.getResponseHeader();
            if (header.getSuccess()) {
                if (response.getConfigCount() > 0) {
//                    response.getConfigList().forEach(System.out::println);
                    LogUtils.d("configList:"+JSON.toJSONString(response.getConfigList()));
                }
            } else {
                // error return by ResponseHeader
                System.err.println(header.getCode() + "," + header.getMessage());
            }
        } catch (StatusRuntimeException e) {
            // error return by Exception
            System.err.println(e.getStatus().getCode() + "," + e.getStatus().getDescription());
            e.printStackTrace();
        }
    }



    public void getAppConfig() {
        GetAppConfigRequest request = GetAppConfigRequest.newBuilder().build();
        try {
            GetAppConfigResponse response = AppServiceGrpc.newBlockingStub(channel).getConfig(request);
            ResponseHeader header = response.getResponseHeader();
            if (header.getSuccess()) {
                if (response.getConfigCount() > 0) {
                LogUtils.d("应用配置："+ JSON.toJSONString(response.getConfigList()));
                }
            } else {
                // error return by ResponseHeader
                System.err.println(header.getCode() + "," + header.getMessage());
            }
        } catch (StatusRuntimeException e) {
            // error return by Exception
            System.err.println(e.getStatus().getCode() + "," + e.getStatus().getDescription());
            e.printStackTrace();
        }
    }


    public void getMeConfig() {
        GetHomeConfigRequest request = GetHomeConfigRequest.newBuilder().build();
        try {
            GetHomeConfigResponse response = HomeServiceGrpc.newBlockingStub(channel).getConfig(request);
            ResponseHeader header = response.getResponseHeader();
            if (header.getSuccess()) {
                if (response.getConfigCount() > 0) {
                   LogUtils.d("我的主页配置："+JSON.toJSONString(response.getConfigList()));
                }
            } else {
                // error return by ResponseHeader
                System.err.println(header.getCode() + "," + header.getMessage());
            }
        } catch (StatusRuntimeException e) {
            // error return by Exception
            System.err.println(e.getStatus().getCode() + "," + e.getStatus().getDescription());
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        mAgentWeb.getWebLifeCycle().onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAgentWeb.getWebLifeCycle().onPause();
    }


    

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
    }
}
