package com.hc.lib.video;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.hc.lib.R;
import com.hc.lib.http.GetRequestListener;
import com.hc.lib.http.GetRequest;
import com.hc.lib.store.LastPlayTimeStore;
import com.makeramen.roundedimageview.RoundedImageView;

import org.json.JSONArray;
import org.json.JSONObject;

public class VideoPauseDialog extends Dialog implements View.OnClickListener {

    private OnPlayItemSelectedListener onPlayItemSelectedListener;
    private boolean hasDialogComplete = false;
    public boolean hasShow = false;
    private boolean videoShowThis = true;
    private Context context;

    //add by xu lin 2018/12/25
    private ImageView btnCollect;
    private ImageView btnResume;
    private FrameLayout imageContainer1;
    private FrameLayout imageContainer2;
    private FrameLayout imageContainer3;
    private RoundedImageView imageView1;
    private RoundedImageView imageView2;
    private RoundedImageView imageView3;
    private TextView title1;
    private TextView title2;
    private TextView title3;


    public VideoPauseDialog(@NonNull Context context, @NonNull boolean hasComplete) {
        super(context, R.style.dialog);
        this.hasDialogComplete = hasComplete;
        this.context = context;
        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_BACK){
                    if(!videoShowThis){
                        dialogDismiss();
                        if(!hasDialogComplete){
                            onPlayItemSelectedListener.playResume(true);
                        }
                        return true;
                    }
                    videoShowThis = false;
                }
                return false;
            }
        });
    }

    public void setHasComplete(boolean hasComplete){
        this.hasDialogComplete = hasComplete;
        if(btnResume == null){
            return;
        }
        if(hasComplete){
            btnResume.setImageResource(R.drawable.restart_play);
        }else{
            btnResume.setImageResource(R.drawable.continue_play);
        }
    }

    public void setOnPlayItemSelectedListener(OnPlayItemSelectedListener listener) {
        this.onPlayItemSelectedListener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View pauseDialogContentView = View.inflate(getContext(), R.layout.guess_your_favirate, null);
        setContentView(pauseDialogContentView);
        btnCollect = pauseDialogContentView.findViewById(R.id.btn_collect_image);
        btnCollect.setOnClickListener(this);
        btnResume = pauseDialogContentView.findViewById(R.id.btn_resume_image);

        //add by xu lin 2018/12/25
        imageContainer1 = pauseDialogContentView.findViewById(R.id.image_container_1);
        imageContainer2 = pauseDialogContentView.findViewById(R.id.image_container_2);
        imageContainer3 = pauseDialogContentView.findViewById(R.id.image_container_3);

        imageView1 = pauseDialogContentView.findViewById(R.id.image_1);
        imageView2 = pauseDialogContentView.findViewById(R.id.image_2);
        imageView3 = pauseDialogContentView.findViewById(R.id.image_3);

        title1 = pauseDialogContentView.findViewById(R.id.title_1);
        title2 = pauseDialogContentView.findViewById(R.id.title_2);
        title3 = pauseDialogContentView.findViewById(R.id.title_3);

        try{
            setOnFocusListener();
        }catch (Exception e){
            e.printStackTrace();
        }

        //add by xu lin 2018/12/25 end
        if(hasDialogComplete){
            btnResume.setImageResource(R.drawable.restart_play);
        }
        setOnClickListener(pauseDialogContentView, R.id.btn_resume_image);
        setOnClickListener(pauseDialogContentView, R.id.btn_exit_image);
        setContentView(pauseDialogContentView);
        setCancelable(false);
    }

    private String getUserName(){
        try{
            Uri queryUri = Uri.parse("content://stbauthinfo/authentication/");
            Cursor cursor = context.getContentResolver().query(queryUri,new String[]{"value"},"name='username'",null,null);
            cursor.moveToFirst();
            String userName = cursor.getString(cursor.getColumnIndexOrThrow("value"));
            return userName;
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    private void getFavoriteData(){
        resetLoadingImage();
        String url ="http://112.35.32.145:8090/index.php?m=Home&c=ApiV2&a=guessFav&uid=" + getUserName();
        new GetRequest().RequestAsync(url,new GetRequestListener(){

            @Override
            public void onResult(final String msg) {
                Activity activity = (Activity)context;
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        executeFavoriteData(msg);
                    }
                });
            }
        });
    }

    private void resetLoadingImage(){
        if(imageView1 != null){
            imageView1.setImageResource(R.drawable.loading);
        }
        if(imageView2 != null){
            imageView2.setImageResource(R.drawable.loading);
        }
        if(imageView3 != null){
            imageView3.setImageResource(R.drawable.loading);
        }
    }

    private void executeFavoriteData(String response){
        try{
            JSONObject jsonObject = new JSONObject(response);
            if(jsonObject.getInt("code") == 0){
                JSONArray dataArray = jsonObject.getJSONArray("data");
                //第一个视频
                Glide.with(context)
                        .load(dataArray.getJSONObject(0).getString("source_image"))
                        .into(imageView1);
                final String videoTitle1 = dataArray.getJSONObject(0).getString("source_name");
                title1.setText(videoTitle1);
                final String sourceId1 = dataArray.getJSONObject(0).getString("source_id");
                imageContainer1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogDismiss();
                        onPlayItemSelectedListener.playFavorite(sourceId1,videoTitle1);
                    }
                });
                //第二个视频
                Glide.with(context)
                        .load(dataArray.getJSONObject(1).getString("source_image"))
                        .into(imageView2);
                final String videoTitle2 = dataArray.getJSONObject(1).getString("source_name");
                title2.setText(videoTitle2);
                final String sourceId2 = dataArray.getJSONObject(1).getString("source_id");
                imageContainer2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogDismiss();
                        onPlayItemSelectedListener.playFavorite(sourceId2,videoTitle2);
                    }
                });
                //第三个视频
                Glide.with(context)
                        .load(dataArray.getJSONObject(2).getString("source_image"))
                        .into(imageView3);
                final String videoTitle3 = dataArray.getJSONObject(2).getString("source_name");
                title3.setText(videoTitle3);
                final String sourceId3 = dataArray.getJSONObject(2).getString("source_id");
                imageContainer3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogDismiss();
                        onPlayItemSelectedListener.playFavorite(sourceId3,videoTitle3);
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void setOnFocusListener() throws Exception{

        imageContainer1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    title1.setTextColor(getContext().getResources().getColor(R.color.pause_title_focus));
                }else{
                    title1.setTextColor(getContext().getResources().getColor(R.color.white));
                }
            }
        });

        imageContainer2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    title2.setTextColor(getContext().getResources().getColor(R.color.pause_title_focus));
                }else{
                    title2.setTextColor(getContext().getResources().getColor(R.color.white));
                }
            }
        });

        imageContainer3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    title3.setTextColor(getContext().getResources().getColor(R.color.pause_title_focus));
                }else{
                    title3.setTextColor(getContext().getResources().getColor(R.color.white));
                }
            }
        });
    }


    private void setOnClickListener(View rootView, int id) {
        rootView.findViewById(id).setOnClickListener(this);
    }

    public void setIsCollected(boolean isCollected) {
        if(btnCollect == null) return;
        if(isCollected) {
            btnCollect.setImageResource(R.drawable.collect_cancel);
        } else {
            btnCollect.setImageResource(R.drawable.collect);
        }
    }

    @Override
    public void onClick(View view) {
        if (onPlayItemSelectedListener == null) {
            return;
        }
        if (view.getId() == R.id.btn_resume_image) {
            dialogDismiss();
            if(hasDialogComplete){
                onPlayItemSelectedListener.playReStart();
            }else{
                onPlayItemSelectedListener.playResume(true);
            }
        } else if (view.getId() == R.id.btn_collect_image) {
            onPlayItemSelectedListener.playCollect();
        } else if (view.getId() == R.id.btn_exit_image) {
            dialogDismiss();
            if(hasDialogComplete){
                onPlayItemSelectedListener.playExit(true);
            }else{
                onPlayItemSelectedListener.playExit(false);
            }

        }
    }

    public void dialogDismiss(){
        dismiss();
        this.hasShow = false;
    }

    @Override
    public void show() {
        super.show();
        getFavoriteData();
        hasShow = true;
        videoShowThis = true;
        imageContainer1.requestFocus();
        //findViewById(R.id.btn_resume).requestFocus();
    }

    /**
     * 暂停播放选项选择监听接口
     */
    public interface OnPlayItemSelectedListener {
        /**
         * 播放继续
         */
        void playReStart();

        /**
         * 播放继续
         */
        void playResume(boolean play);

        /**
         * 收藏影片
         */
        void playCollect();

        /**
         * 退出播放
         */
        void playExit(boolean Complete);


        /**
         * 播放猜你喜欢视频
         */
        void playFavorite(String sourceId,String title);
    }
}
