package com.efounder.chat.activity;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.utils.FileSizeUtil;
import com.efounder.chat.widget.MovieRecorderView;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;

import java.io.File;
import java.util.List;

public class RecorderActivity extends BaseActivity {
    private MovieRecorderView mRecorderView;
    private Button mShootBtn;
    private boolean isFinish = true;
    private Button backButton;
    private ImageView ivSelectAlbum;

    private int mShowLocal;
    //从相册选视频
    public final static int SELECT_VIDEO = 1;

    @Override
    public boolean immersionBarEnabled() {
        //设置全屏 透明状态栏
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_record);

        mShowLocal = getIntent().getIntExtra("showLocal", 0);

        mRecorderView = (MovieRecorderView) findViewById(R.id.movieRecorderView);
        mShootBtn = (Button) findViewById(R.id.shoot_button);
        backButton = (Button) findViewById(R.id.button_back);
        ivSelectAlbum = (ImageView) findViewById(R.id.iv_select_album);

        if (mShowLocal == SELECT_VIDEO) {
            ivSelectAlbum.setVisibility(View.VISIBLE);
        }

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mShootBtn.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mRecorderView.record(new MovieRecorderView.OnRecordFinishListener() {

                        @Override
                        public void onRecordFinish() {
                            handler.sendEmptyMessage(1);
                        }
                    });
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (mRecorderView.getTimeCount() > 1) {
                        handler.sendEmptyMessage(1);
                    } else {
                        if (mRecorderView.getmRecordFile() != null)
                            mRecorderView.getmRecordFile().delete();
                        mRecorderView.stop();
                        Toast.makeText(RecorderActivity.this, R.string.wrchatview_video_record_short, Toast.LENGTH_SHORT).show();
                        try {
                            mRecorderView.initCamera();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                return true;
            }
        });

        ivSelectAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 666);
            }
        });

        checkHasPermission();
    }

    private void checkHasPermission() {
        if (!EasyPermissionUtils.checkRecordVideoPermission()) {
            EasyPermissionUtils.requestRecordVideoPermission(this);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        isFinish = true;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        isFinish = false;
        mRecorderView.stop();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            mRecorderView.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            finishActivity();
        }
    };

    private void finishActivity() {
        if (isFinish) {
            mRecorderView.stop();
            isFinish = false;
            // 返回到播放页面
   /*         Intent intent = new Intent();
            Log.d("TAG", mRecorderView.getmRecordFile().getAbsolutePath());
            intent.putExtra("path", mRecorderView.getmRecordFile().getAbsolutePath());
            intent.putExtra("videoTime", mRecorderView.getTimeCount() + "");
            setResult(RESULT_OK, intent);*/
            if (mRecorderView.getmRecordFile().getAbsolutePath() == null) {
                ToastUtil.showToast(this, R.string.wrchatview_record_fail);
                return;
            }

            try {
                File file = new File(mRecorderView.getmRecordFile().getAbsolutePath());
                if (file.exists() && FileSizeUtil.getFileSize(file) < 500) {
                    ToastUtil.showToast(this, R.string.wrchatview_record_fail);
                    return;
                }

            } catch (Exception e) {
                e.printStackTrace();
                ToastUtil.showToast(this, R.string.wrchatview_record_fail);
                return;
            }

            VideoReviewActivity.open(mRecorderView.getmRecordFile().getAbsolutePath(), mRecorderView.getTimeCount() + "", 200, this);

        } else {
//            close();

        }
    }

    private void close() {
        finish();
        overridePendingTransition(R.anim.push_top_in, R.anim.push_bottom_out);
    }

    @Override
    public void onBackPressed() {
        close();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    /**
     * 录制完成回调
     *
     * @author liuyinjun
     * @date 2015-2-9
     */
    public interface OnShootCompletionListener {
         void OnShootSuccess(String path, int second);

         void OnShootFailure();
    }

  /*  //  private Button btnVideo;

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

       *//* btnVideo = (Button) findViewById(R.id.btn_video);

        btnVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                String url = createFilePath("QDbzxt_video");
                File file = new File(url,"mov_"+getCurrentDate()+".mp4");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); // 设置存储路径
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // 设置保存质量
                intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10); // 设置限制时长
                //intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT,100000L); // 设置限制大小
                startActivityForResult(intent, 0x123);

            }
        });*//*
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }*/

  /*  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0x123:
                if(resultCode == RESULT_OK) {
                    Toast.makeText(this, "Video saved to:\n" +
                            data.getData(), Toast.LENGTH_LONG).show();
                    // 获取第一帧图片

                }
                break;
        }
    }

    *//**
     * 创建文件夹路径
     * @param folderName　文件夹名称
     * @return 文件夹路径
     *//*
    public static String createFilePath(String folderName) {
        File file = new File(android.os.Environment.getExternalStorageDirectory()+"/"+folderName);
        file.mkdir();
        String path = file.getPath();
        return path;
    }

    */

    /**
     * 获取当前时间
     *
     * @return 日期的字符串信息
     *//*
    public static String getCurrentDate() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String strDate = dateFormat.format(new Date());
        return strDate;
    }*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200) {
            if (resultCode == RESULT_OK && data != null) {
                Intent intent = new Intent();
                Log.d("TAG", mRecorderView.getmRecordFile().getAbsolutePath());
                intent.putExtra("path", mRecorderView.getmRecordFile().getAbsolutePath());
                intent.putExtra("videoTime", mRecorderView.getTimeCount() + "");
                setResult(RESULT_OK, intent);
            }
        } else if (requestCode == 666) {
            if (resultCode == RESULT_OK && data != null) {
                Uri selectedVideo = data.getData();
                String[] filePathColumn = {MediaStore.Video.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedVideo,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String path = cursor.getString(columnIndex);
                Intent intent = new Intent();
                intent.putExtra("path", cursor.getString(columnIndex));
                setResult(RESULT_OK, intent);
                cursor.close();
            }
        }
        close();

    }
}
