package ai.pai.lensman.main;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
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.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.UploadService;

public class MainPresenter implements MainContract.Presenter,BaseInteractor.InteractorListener<ArrayList<String>>,UploadService.PhotoUploadListener {

    private MainContract.View uploadView;
    private ArrayList<SessionBean> sessionList;
    private String lensmanId;
    private int sessionSeq;
    private ArrayList<String> sessionIds;
    private FetchSessionIdsInteractor interactor;
    private ServiceConnection serviceConnection;

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

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };
    }


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

        if(sessionIds==null|| sessionIds.size()<20){
            interactor.startJob();
        }
        if(sessionIds==null || sessionIds.size()<1){
            uploadView.setNewSessionBtnEnabled(false);
        }else{
            uploadView.setNewSessionBtnEnabled(true);
        }
        sessionList = DBService.getInstance().getSessionBeanListByDay(getSessionDateInLongFormat());
        if(sessionList.size()==0){
            uploadView.showEmptyView();
        }else{
            uploadView.showSessionViews();
            uploadView.refreshSessionViews(sessionList);
        }
        sessionSeq = sessionList.size();

        App.getAppContext().startService(new Intent(App.getAppContext(), UploadService.class));
        App.getAppContext().bindService(new Intent(App.getAppContext(),UploadService.class),serviceConnection, Context.BIND_AUTO_CREATE);
        uploadView.showOrderSnackBar();
    }

    @Override
    public void stop() {
        App.getAppContext().unbindService(serviceConnection);
    }

    @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);
        uploadView.setNewSessionBtnEnabled(true);
        uploadView.showBoxConnectedView();
    }

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

    }


    @Override
    public synchronized void onPhotoUploaded(PhotoBean bean) {
        int position = sessionList.size()-bean.sessionSeq;
        if(position < 0 || position>=sessionList.size()){
            return;
        }
        LogHelper.d("czy","onPhotoUploaded and notify UI change at "+position);
        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){
                    LogHelper.d("czy","onPhotoUploaded and found data change "+position);
                    photoBean.uploadStatus = PhotoBean.UploadStatus.STATUS_SUCCESS;
                    break;
                }
            }
        }
        sessionBean.sessionPhotos = photoList;
        uploadView.updateSessionUploadViewAt(position);
    }

    @Override
    public synchronized void onPhotoUploadError(PhotoBean bean) {
        int position = sessionList.size()-bean.sessionSeq;
        if(position < 0 || position>=sessionList.size()){
            return;
        }
        LogHelper.d("czy","onPhotoUploadError and notify UI change at "+position);
        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){
                    LogHelper.d("czy","onPhotoUploaded and found data change "+position);
                    photoBean.uploadStatus = PhotoBean.UploadStatus.STATUS_ERROR;
                    break;
                }
            }
        }
        sessionBean.sessionPhotos = photoList;
        uploadView.updateSessionUploadViewAt(position);
    }
}
