//Copyright 2018 Huawei Technologies Co.,Ltd.
package com.huawei.mediacloud.livepushdemo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.meicam.sdk.NvsStreamingContext;
import com.huawei.mediacloud.livepushdemo.base.BaseActivity;
import com.huawei.mediacloud.livepushdemo.capture.CaptureActivity;
import com.huawei.mediacloud.livepushdemo.main.OnItemClickListener;
import com.huawei.mediacloud.livepushdemo.utils.AppManager;
import com.huawei.mediacloud.livepushdemo.utils.Constants;
import com.huawei.mediacloud.livepushdemo.utils.ParameterSettingValues;
import com.huawei.mediacloud.livepushdemo.utils.SpUtil;
import com.huawei.mediacloud.livepushdemo.utils.Util;
import com.huawei.mediacloud.livepushdemo.utils.asset.NvAssetManager;
import com.huawei.mediacloud.livepushdemo.utils.authpack;

import static android.view.View.VISIBLE;


public class MainActivity extends BaseActivity implements OnItemClickListener {
    public static final int REQUEST_CAMERA_PERMISSION_CODE = 200;
    public static final int REQUEST_RECORD_AUDIO_PERMISSION_CODE = 201;
    public static final int REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_CODE = 202;
    public static final int REQUEST_READ_EXTERNAL_STORAGE_PERMISSION_CODE = 203;
    public static final int REQUEST_READ_PHONE_STATE_PERMISSION_CODE = 204;

    private boolean m_waitFlag = false;
    private RelativeLayout layoutVideoCapture;
    private LinearLayout main_set_layout;
    private boolean isSetupVisable;

    private Button btn360;
    private Button btn540;
    private Button btn720;

    private Button btnSetup;

    private EditText EtBitrate;
    private EditText EtGop;

    private int encodeWidth;
    private int encodeBitrate;
    private int encodeGop;

    private boolean m_canUseARFace = false; // 人脸特效是否可用的标识
    private TextView mainVersionNumber;
    private boolean mPermissionGranted = false;
    private View clickedView = null;

    @Override
    protected int initRootView() {
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return R.layout.activity_main;
        }
        //初始化
        String licensePath = "";
        NvsStreamingContext.init(MainActivity.this, licensePath, NvsStreamingContext.STREAMING_CONTEXT_FLAG_SUPPORT_4K_EDIT);
        NvAssetManager.init(MainActivity.this);//素材管理器初始化
        return R.layout.activity_main;
    }

    private void checkAllPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)) {
                if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO)) {
                    if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
                            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE)) {
                                mPermissionGranted = true;
                            } else {
                                requestPermissions(new String[]{android.Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE_PERMISSION_CODE);
                            }
                        } else {
                            requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE_PERMISSION_CODE);
                        }
                    } else {
                        requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_CODE);
                    }
                } else {
                    requestPermissions(new String[]{android.Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO_PERMISSION_CODE);
                }
            } else {
                requestPermissions(new String[]{android.Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_CODE);
            }
        } else {
            mPermissionGranted = true;
        }
    }

    @Override
    protected void initTitle() {

    }

    @Override
    protected void initViews() {
        encodeWidth = 540;
        encodeBitrate = 600;
        encodeGop = 20;
        isSetupVisable = false;

        layoutVideoCapture = (RelativeLayout) findViewById(R.id.layout_video_capture);
        main_set_layout = (LinearLayout) findViewById(R.id.main_set_layout);
//        layout_360 = (LinearLayout) findViewById(R.id.layout_360);
//        layout_480 = (LinearLayout) findViewById(R.id.layout_480);
//        layout_720 = (LinearLayout) findViewById(R.id.layout_720);

        btn360 = (Button)findViewById(R.id.btn360);
        btn540 = (Button)findViewById(R.id.btn540);
        btn720 = (Button)findViewById(R.id.btn720);

        btnSetup = (Button)findViewById(R.id.btnSetup);

        EtBitrate = (EditText) findViewById(R.id.EditBitrate);
        EtGop = (EditText) findViewById(R.id.EditGop);

        EtBitrate.setText(""+encodeBitrate);
        EtGop.setText(""+encodeGop);

        mainVersionNumber = (TextView) findViewById(R.id.main_versionNumber);
    }

    @Override
    protected void initData() {
        ParameterSettingValues parameterValues = (ParameterSettingValues) SpUtil.getObjectFromShare(getApplicationContext(), Constants.KEY_PARAMTER);
        if (parameterValues != null) {  // 本地没有存储设置的参数，设置默认值
            ParameterSettingValues.setParameterValues(parameterValues);
        }
        // 探测人脸特效是否可用
        try {
            Class.forName("com.meicam.sdk.NvsFaceEffectV1Detector");
            m_canUseARFace = true;
        } catch (ClassNotFoundException e) {
            m_canUseARFace = false;
            e.printStackTrace();
        }
        Log.e("m_canUseARFace","m_canUseARFace:"+m_canUseARFace);
        // 初始化AR Effect，全局只需一次
        if (m_canUseARFace) {
            com.meicam.sdk.NvsFaceEffectV1.setup("assets:/NvFaceData.asset", authpack.A());
            com.meicam.sdk.NvsFaceEffectV1.setMaxFaces(2);
        }
//        initFragmentAndView();
        NvsStreamingContext.SdkVersion sdkVersion = NvsStreamingContext.getInstance().getSdkVersion();
        String sdkVersionNum = String.valueOf(sdkVersion.majorVersion) + "." + String.valueOf(sdkVersion.minorVersion) + "." + String.valueOf(sdkVersion.revisionNumber);
        mainVersionNumber.setText(String.format(getResources().getString(R.string.versionNumber)));

    }

    @Override
    protected void initListener() {
        layoutVideoCapture.setOnClickListener(this);

        btn360.setOnClickListener(this);
        btn540.setOnClickListener(this);
        btn720.setOnClickListener(this);

        btnSetup.setOnClickListener(this);
        checkAllPermission();
    }

    @Override
    public void onClick(View view) {
        if(!mPermissionGranted){//没有权限，则请求权限
            clickedView = view;
            checkAllPermission();
        }else {
//            if (m_waitFlag)
//                return;
//             m_waitFlag = true;
            doClick(view);
        }
    }

    private void doClick(View view){
        Log.e("doclick", "doClick: doClick");
        if(view == null)
            return;
        Bundle bundle = new Bundle();
        switch (view.getId()) {

            case R.id.layout_video_capture://拍摄

                bundle.putBoolean(Constants.CAN_USE_ARFACE_FROM_MAIN, m_canUseARFace);
                bundle.putInt("encodeWidth",encodeWidth);
                bundle.putInt("encodeBitrate",Integer.parseInt(EtBitrate.getText().toString()));
                bundle.putInt("encodeGop",Integer.parseInt(EtGop.getText().toString()));
                AppManager.getInstance().jumpActivity(this, CaptureActivity.class, bundle);
                break;
            case R.id.btn360://分辨率360
                encodeWidth = 360;
                btn360.setBackgroundColor(Color.parseColor("#66CDAA"));
                btn540.setBackgroundColor(Color.parseColor("#ffffff"));
                btn720.setBackgroundColor(Color.parseColor("#ffffff"));
                Log.e("doclick", "doClick: btn360");
                break;
            case R.id.btn540://分辨率480
                encodeWidth = 540;
                btn360.setBackgroundColor(Color.parseColor("#ffffff"));
                btn540.setBackgroundColor(Color.parseColor("#66CDAA"));
                btn720.setBackgroundColor(Color.parseColor("#ffffff"));
                Log.e("doclick", "doClick: btn480");
                break;
            case R.id.btn720://分辨率720
                encodeWidth = 720;
                btn360.setBackgroundColor(Color.parseColor("#ffffff"));
                btn540.setBackgroundColor(Color.parseColor("#ffffff"));
                btn720.setBackgroundColor(Color.parseColor("#66CDAA"));
                Log.e("doclick", "doClick: btn720");
                break;

            case R.id.btnSetup://跳转设置页面
                if(isSetupVisable) {
                    main_set_layout.setVisibility(View.GONE);
                    isSetupVisable = false;
                }
                else {
                    main_set_layout.setVisibility(VISIBLE);
                    isSetupVisable =true;
                }
                Log.e("doclick", "doClick: VISIBLE");
//                bundle.putBoolean(Constants.CAN_USE_ARFACE_FROM_MAIN, m_canUseARFace);
//                bundle.putInt("encodeWidth",encodeWidth);
//                bundle.putInt("encodeBitrate",Integer.parseInt(EtBitrate.getText().toString()));
//                bundle.putInt("encodeGop",Integer.parseInt(EtGop.getText().toString()));
//                AppManager.getInstance().jumpActivity(this, CaptureActivity.class, bundle);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        Util.clearRecordAudioData();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        m_waitFlag = false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return;

        if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED)
            return;

        switch (requestCode) {
            case REQUEST_CAMERA_PERMISSION_CODE:
                if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO)) {
                    if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                            mPermissionGranted = true;
                            doClick(clickedView);
                        } else
                            requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE_PERMISSION_CODE);
                    } else
                        requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_CODE);
                } else {
                    requestPermissions(new String[]{android.Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO_PERMISSION_CODE);
                }
                break;
            case REQUEST_RECORD_AUDIO_PERMISSION_CODE:
                if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        mPermissionGranted = true;
                        doClick(clickedView);
                    } else
                        requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE_PERMISSION_CODE);
                } else
                    requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_CODE);
                break;
            case REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_CODE:
                if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    mPermissionGranted = true;
                    doClick(clickedView);
                } else
                    requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE_PERMISSION_CODE);
                break;
            case REQUEST_READ_EXTERNAL_STORAGE_PERMISSION_CODE:
                mPermissionGranted = true;
                doClick(clickedView);
                break;
        }
    }
}
