package com.mapotempo.fleet.core;

import com.couchbase.lite.*;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.AuthenticatorFactory;
import com.couchbase.lite.replicator.Replication;
import com.mapotempo.fleet.core.exception.CoreException;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * DatabaseHandler.
 */
public class DatabaseHandler {

    private boolean mConnexionStatus = false;

    private Context mContext;

    private Manager mManager;

    public Database mDatabase;

    private String mDbname = "mydbname";

    private URL url = null;

    private String mUser;

    private String mPassword;

    private Replication mPusher, mPuller;

    public DatabaseHandler(String user, String password, String syncGatewayUrl, Context context) throws CoreException {
        this.mUser = user;
        this.mPassword = password;
        this.mContext = context;
        try {
            this.mManager = new Manager(mContext, Manager.DEFAULT_OPTIONS);
        } catch (IOException e) {
            throw new CoreException(e);
        }
        mDbname = user + "_database";
        try {
            this.mDatabase = mManager.getDatabase(mDbname);
        } catch (CouchbaseLiteException e) {
            throw new CoreException(e);
        }

        initConnexion(syncGatewayUrl);
    }

    private void initConnexion(String syncGatewayUrl) throws CoreException
    {
        // CONNEXION
        try{
            url = new URL(syncGatewayUrl);
        } catch (MalformedURLException e){
           throw new CoreException(e);
        }


        mPusher = mDatabase.createPushReplication(url);

        mPusher.setContinuous(true); // Runs forever in the background
        mPusher.addChangeListener(new Replication.ChangeListener() {
            @Override
            public void changed(Replication.ChangeEvent changeEvent) {
                System.out.println("pusher changed listener");
            }
        });
        mPuller = mDatabase.createPullReplication(url);

        mPuller.setContinuous(true); // Runs forever in the background
        mPuller.addChangeListener(new Replication.ChangeListener() {
            @Override
            public void changed(Replication.ChangeEvent changeEvent) {
                System.out.println("puller changed listener");
            }
        });

        // USER AUTH
        Authenticator authenticator = AuthenticatorFactory.createBasicAuthenticator(mUser, mPassword);
        mPusher.setAuthenticator(authenticator);
        //   mPusher.goOffline();
        mPuller.setAuthenticator(authenticator);
        //   mPuller.goOffline();

        mPusher.start();
        mPuller.start();
    }

    public boolean goOnline()
    {
        if(mConnexionStatus == false) {
            mPuller.goOnline();
            mPusher.goOnline();
            mConnexionStatus = true;
        }
        return mConnexionStatus;
    }

    public boolean goOffline()
    {
        if(mConnexionStatus == true) {
            mPuller.goOffline();
            mPusher.goOffline();
            mConnexionStatus = false;
        }
        return mConnexionStatus;
    }

    public void printAllData()
    {
        try {
            // Let's find the documents that have conflicts so we can resolve them:
            Query query = mDatabase.createAllDocumentsQuery();
            query.setAllDocsMode(Query.AllDocsMode.ALL_DOCS);
            List<Object> res = new ArrayList<Object>();
            QueryEnumerator result = query.run();
            for (Iterator<QueryRow> it = result; it.hasNext(); ) {
                QueryRow row = it.next();
                String docId = row.getDocumentId();
                Document doc = mDatabase.getDocument(docId );
                System.out.println(doc.getProperties().toString());
            }
        } catch (CouchbaseLiteException e) {
            e.printStackTrace();
        }
        return;
    }
}

@@ -202,24 +202,74 @@
 eplication;%0A
+import com.mapotempo.fleet.core.utils.DateHelper;%0A
 import com.m
@@ -1748,16 +1748,49 @@
      %7D%0A%0A
+        // Pusher and Puller sync
 %0A       
@@ -1830,33 +1830,32 @@
 plication(url);%0A
-%0A
         mPusher.
@@ -2216,17 +2216,16 @@
 n(url);%0A
-%0A
         
@@ -2716,42 +2716,8 @@
 r);%0A
-        //   mPusher.goOffline();%0A
     
@@ -2753,32 +2753,33 @@
 authenticator);%0A
+%0A
         //   mPu
@@ -2777,78 +2777,504 @@
  // 
-  mPuller.goOffline();%0A%0A        mPusher.start();%0A        mPuller.start
+Subscribing to the 3 next days date.%0A        ArrayList%3CString%3E channels = new ArrayList%3C%3E();%0A        channels.add(%22static:%22 + DateHelper.dateForChannel(0));%0A        channels.add(%22static:%22 + DateHelper.dateForChannel(1));%0A        channels.add(%22static:%22 + DateHelper.dateForChannel(2));%0A        mPuller.setChannels(channels);%0A%0A        // Start synchronisation%0A        mPusher.start();%0A        mPuller.start();%0A%0A        // TODO go offline ?%0A        //mPusher.goOffline();%0A        //mPuller.goOffline
 ();%0A

Add channel sync on the next 3 days.