package ai.pai.lensman.main;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.os.IBinder;

import com.android.common.utils.LogHelper;
import com.android.common.utils.NetworkUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import ai.pai.lensman.App;
import ai.pai.lensman.R;
import ai.pai.lensman.base.BaseInteractor;
import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.bean.SessionBean;
import ai.pai.lensman.db.DBService;
import ai.pai.lensman.db.Preferences;
import ai.pai.lensman.service.OrderDealService;
import ai.pai.lensman.service.UploadService;

class MainPresenter implements MainContract.Presenter,BaseInteractor.InteractorListener<ArrayList<String>>,
        UploadService.PhotoUploadListener, QueryBoxStatusInteractor.BoxStatusListener,OrderDealService.OrderServiceListener {

    private int sessionSeq;
    private String lensmanId;
    private ArrayList<String> sessionIds;

    private ArrayList<SessionBean> sessionList;

    private MainContract.View view;
    private FetchSessionIdsInteractor interactor;
    private QueryBoxStatusInteractor boxStatusInteractor;

    private ServiceConnection uploadServiceConnection;
    private ServiceConnection orderServiceConnection;

    private boolean isBoxConnected = true;


    private BroadcastReceiver wifiReceiver  = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                if(NetworkUtil.isWifiConnected(context)){
                    view.showBoxConnectedView();
                }else{
                    isBoxConnected = false;
                    view.showBoxDisconnectedView();
                }
            }
        }
    };

     MainPresenter(MainContract.View view){
        this.view = view;
        this.lensmanId = Preferences.getInstance().getLensManId();
        sessionIds = new ArrayList<>();
        interactor = new FetchSessionIdsInteractor(lensmanId,100,this);
        boxStatusInteractor = new QueryBoxStatusInteractor(this);
        uploadServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                ((UploadService.MyBinder) iBinder).getService().setPhotoUploadListener(MainPresenter.this);
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };

         orderServiceConnection = new ServiceConnection() {
             @Override
             public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                 ((OrderDealService.OrderServiceBinder) iBinder).getService().setOrderServiceListener(MainPresenter.this);
             }

             @Override
             public void onServiceDisconnected(ComponentName componentName) {

             }
         };
    }


    @Override
    public void start() {
        if(NetworkUtil.isWifiConnected(App.getAppContext())){
            view.showBoxConnectedView();
        }else{
            view.showBoxDisconnectedView();
        }

        if(sessionIds==null|| sessionIds.size()<20){
            interactor.startJob();
        }
        if(sessionIds==null || sessionIds.size()<1){
            view.setNewSessionBtnEnabled(false);
            view.showSnackBar(R.string.prepare_in_processing);
        }else{
            view.setNewSessionBtnEnabled(true);
        }
        sessionList = DBService.getInstance().getSessionBeanListByDay(getSessionDateInLongFormat());
        if(sessionList.size()==0){
            view.showEmptyView();
        }else{
            view.showSessionViews();
            view.refreshSessionViews(sessionList);
        }
        sessionSeq = sessionList.size();
        registerWifiChangeReceiver();
        boxStatusInteractor.startJob();
        App.getAppContext().startService(new Intent(App.getAppContext(), OrderDealService.class));
        App.getAppContext().bindService(new Intent(App.getAppContext(),OrderDealService.class),
                orderServiceConnection, Context.BIND_AUTO_CREATE);
        App.getAppContext().startService(new Intent(App.getAppContext(), UploadService.class));
        App.getAppContext().bindService(new Intent(App.getAppContext(),UploadService.class),
                uploadServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void stop() {
        boxStatusInteractor.cancelJob();
        App.getAppContext().unbindService(uploadServiceConnection);
        App.getAppContext().unbindService(orderServiceConnection);
        App.getAppContext().unregisterReceiver(wifiReceiver);
    }

    @Override
    public SessionBean createNewSession() {

        SessionBean sessionBean = new SessionBean();
        sessionBean.lensmanId = lensmanId;
        sessionBean.sessionDate=getSessionDateInLongFormat();
        sessionBean.sessionSeq = sessionSeq+1;
        sessionBean.sessionId =sessionIds.get(0);
        sessionList.add(sessionBean);
        sessionIds.remove(0);
        return sessionBean;
    }

    private long getSessionDateInLongFormat(){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String dateStr = format.format(new Date());
        return Long.parseLong(dateStr);
    }

    @Override
    public void onInteractSuccess(ArrayList<String> sessionIds) {
        this.sessionIds.addAll(sessionIds);
        view.setNewSessionBtnEnabled(true);
        view.showBoxConnectedView();
    }

    @Override
    public void onInteractFail(String errorMsg) {
        if(NetworkUtil.isWifiConnected(App.getAppContext())){
            interactor.startJob();
        }else{
            view.showBoxDisconnectedView();
        }

    }


    @Override
    public synchronized void onPhotoUploaded(PhotoBean bean) {
        int position = sessionList.size()-bean.sessionSeq;
        if(position < 0 || position>=sessionList.size()){
            return;
        }
        SessionBean sessionBean = sessionList.get(position);
        ArrayList<PhotoBean> photoList = sessionBean.sessionPhotos;
        if(photoList==null || photoList.size()==0){
            photoList = new ArrayList<>();
            photoList.add(bean);
        }else{
            for(PhotoBean photoBean : photoList){
                if(photoBean.photoId == bean.photoId){
                    photoBean.uploadStatus = PhotoBean.UploadStatus.STATUS_SUCCESS;
                    break;
                }
            }
        }
        sessionBean.sessionPhotos = photoList;
        view.updateSessionUploadViewAt(position);
    }

    @Override
    public synchronized void onPhotoUploadError(PhotoBean bean) {
        int position = sessionList.size()-bean.sessionSeq;
        if(position < 0 || position>=sessionList.size()){
            return;
        }
        SessionBean sessionBean = sessionList.get(position);
        ArrayList<PhotoBean> photoList = sessionBean.sessionPhotos;
        if(photoList==null || photoList.size()==0){
            photoList = new ArrayList<>();
            photoList.add(bean);
        }else{
            for(PhotoBean photoBean : photoList){
                if(photoBean.photoId == bean.photoId){
                    photoBean.uploadStatus = PhotoBean.UploadStatus.STATUS_ERROR;
                    break;
                }
            }
        }
        sessionBean.sessionPhotos = photoList;
        view.updateSessionUploadViewAt(position);
    }

    private void registerWifiChangeReceiver() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        App.getAppContext().registerReceiver(wifiReceiver,filter);
    }


    @Override
    public void onBoxStatusFetched(String boxNo, String boxStatus, String boxStatusCode) {
        if("0".equals(boxStatusCode)){
            isBoxConnected = true;
            view.showBoxConnectedView();
        }else{
            isBoxConnected = false;
            view.showBoxDisconnectedView();
        }
    }

    @Override
    public void onOrderArrived() {
        if(!isBoxConnected){
            view.showSnackBar(R.string.new_order_and_check_box);
        }
    }

    @Override
    public void onOrderCompleted() {

    }
}
