package ai.pai.lensman.session;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.common.utils.LogHelper;
import com.android.common.utils.NetworkUtil;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

import ai.pai.lensman.R;
import ai.pai.lensman.activities.SessionQRCodeActivity;
import ai.pai.lensman.base.BaseActivity;
import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.bean.SessionBean;
import ai.pai.lensman.qrcode.QRCaptureActivity;
import ai.pai.lensman.utils.UmengEvent;
import ai.pai.lensman.views.ExitSessionConfirmPopup;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SessionActivity extends BaseActivity implements SessionContract.View ,View.OnClickListener{

    @BindView(R.id.icon_no_data)         View noPhotoLayout;
    @BindView(R.id.title_bar_middle_txt) TextView titleTextView;
    @BindView(R.id.recycler_view_photos) RecyclerView photosRecyclerView;
    @BindView(R.id.iv_scan)              ImageView qrcodeScanBtn;
    @BindView(R.id.layout_device_status) View deviceConnectLayout;
    @BindView(R.id.iv_box)              ImageView boxIndicator;
    @BindView(R.id.iv_box_phone_line)   ImageView boxPhoneLineIndicator;
    @BindView(R.id.iv_camera)           ImageView cameraIndicator;
    @BindView(R.id.iv_camera_box_line)  ImageView cameraBoxLineIndicator;
    @BindView(R.id.iv_phone)            ImageView phoneIndicator;
    private PhotoRecyclerAdapter adapter;
    private  SessionBean sessionBean;
    private SessionContract.Presenter presenter;
    private static final int JOIN_REQUEST_CODE = 3002;

    private ItemTouchHelper.Callback mCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.RIGHT|ItemTouchHelper.LEFT) {

        @Override
        public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            int position = viewHolder.getAdapterPosition();
            PhotoBean photoBean = adapter.getPhotoAt(position);
            if(photoBean==null){
                return;
            }
            if(photoBean.canDelete){
                presenter.swipeToDeletePhoto(position);
                adapter.removePhotoAtIndex(position);
            }else{
                showToast(getString(R.string.can_not_delete));
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_session);
        unbinder = ButterKnife.bind(this);
        sessionBean =(SessionBean)getIntent().getSerializableExtra("session");
        presenter = new SessionPresenter(sessionBean,this);

        titleTextView.setText(getString(R.string.scene)+sessionBean.sessionSeq);
        adapter = new PhotoRecyclerAdapter(this);

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        photosRecyclerView.setLayoutManager(layoutManager);
        photosRecyclerView.setAdapter(adapter);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(mCallback);
        itemTouchHelper.attachToRecyclerView(photosRecyclerView);

        presenter.start();
        String LOG_PATH = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/lensman/logs/";
        if(!new File(LOG_PATH).exists()&&!new File(LOG_PATH).mkdirs()){
            Toast.makeText(this,R.string.sdcard_fail,Toast.LENGTH_SHORT).show();
        }
        LogHelper.d(TAG,"onCreate");
        LogHelper.d(TAG,"session info = "+sessionBean);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.stop();
        LogHelper.d(TAG,"onDestroy");
    }

    @OnClick(R.id.iv_scan)
    void scanToFetchSessionQR(){
        MobclickAgent.onEvent(this, UmengEvent.session_scan_qr_btn_click);
        Intent intent = new Intent(SessionActivity.this, QRCaptureActivity.class);
        startActivityForResult(intent, JOIN_REQUEST_CODE);

    }

    @OnClick(R.id.iv_qrcode)
    void showQRCodeForSession(){
        MobclickAgent.onEvent(this, UmengEvent.session_view_qr_btn_click);
        Intent intent = new Intent(this,SessionQRCodeActivity.class);
        intent.putExtra("qrcode",sessionBean.sessionId);
        startActivity(intent);
    }

    @OnClick(R.id.title_bar_back_layout)
    void backToMain(){
       new ExitSessionConfirmPopup(this,this).showPopupWindow();
    }

    @OnClick(R.id.btn_session_complete)
    void onSessionComplete(){
        MobclickAgent.onEvent(this, UmengEvent.session_finish_btn_click);
        new ExitSessionConfirmPopup(this,this).showPopupWindow();
    }

    @Override
    public synchronized void addNewPhoto(final PhotoBean bean) {
        LogHelper.d(TAG,"addNewPhoto to UI "+bean);
        adapter.addPhotoBean(bean);
        photosRecyclerView.smoothScrollToPosition(0);
    }

    @Override
    public void showPhotoRecyclerView() {
        qrcodeScanBtn.setVisibility(View.GONE);
        noPhotoLayout.setVisibility(View.GONE);
        photosRecyclerView.setVisibility(View.VISIBLE);
    }

    @Override
    public void showEmptyView() {
        qrcodeScanBtn.setVisibility(View.VISIBLE);
        photosRecyclerView.setVisibility(View.GONE);
        noPhotoLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void showToast(String toast) {
        Toast.makeText(this,toast,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showBoxDisconnectedView(int errorCode,String errorMsg) {
        deviceConnectLayout.setVisibility(View.VISIBLE);
        boxIndicator.setImageResource(R.drawable.box_ok);
        boxPhoneLineIndicator.setImageResource(R.drawable.link_ok);
        cameraBoxLineIndicator.setImageResource(R.drawable.link_ok);
        cameraIndicator.setImageResource(R.drawable.camera_ok);
        phoneIndicator.setImageResource(R.drawable.network_ok);
        switch (errorCode){
            case 201:
            case 202:
            case 203:
                boxIndicator.setImageResource(R.drawable.box_error);
                break;
            case 101:
                cameraBoxLineIndicator.setImageResource(R.drawable.link_error);
                break;
        }
        if(!NetworkUtil.isWifiConnected(this)){
            boxPhoneLineIndicator.setImageResource(R.drawable.link_error);
            phoneIndicator.setImageResource(R.drawable.network_error);
        }
        Toast.makeText(this,NetworkUtil.isWifiConnected(this) ? errorMsg :
                getString(R.string.network_disconnect),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showBoxConnectedView() {
        deviceConnectLayout.setVisibility(View.GONE);
    }

    @Override
    public void refreshUploadTimeHint() {
        if(adapter!=null && photosRecyclerView!=null && photosRecyclerView.getVisibility()==View.VISIBLE){
            photosRecyclerView.post(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        if (resultCode == Activity.RESULT_OK) {
            if (data == null || data.getStringExtra("info") == null) {
                return;
            }
            String qrInfo = data.getStringExtra("info");
            if(qrInfo.contains("pai.ai/g/")||qrInfo.contains("xfoto.com.cn/g/")){
                String groupId = qrInfo.substring(qrInfo.lastIndexOf("/")+1);
                presenter.addSessionPhotos2Group(groupId);
            }else{
                presenter.change2QRCodeSessionId(data.getStringExtra("info"));
            }
        }
    }

    @Override
    public void onClick(View view) {
       if(view.getId()==R.id.btn_exit_session_confirm){
            presenter.stop();
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        new ExitSessionConfirmPopup(this,this).showPopupWindow();
    }


}
