package dp.mendelu.roman.diplomkaapp42;

import android.app.Activity;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.shephertz.app42.paas.sdk.android.App42API;
import com.shephertz.app42.paas.sdk.android.App42Response;
import com.shephertz.app42.paas.sdk.android.storage.Storage;
import com.shephertz.app42.paas.sdk.android.storage.StorageService;

import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * synchronizace celeho cloudu do lokal. db
 * findAllDocuments() from cloud
 * destroy local database, set data from cloud
 */
public class AsyncLoadJSONDoc extends AsyncTask<URL, Integer, ArrayList<Storage.JSONDocument>> {
    //DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSS'Z'");
    //Date date = new Date();


    private static final String TAG = "AsyncLoadJSONDoc";
    Activity mActivity;
    Context mContext, pomContext;

    /**
     * Predani z activity
     * @param activity
     */
    public AsyncLoadJSONDoc(Activity activity){
        mActivity = activity;
    }

    /**
     * Predani ze sluzby
     * @param context
     */
    public AsyncLoadJSONDoc(Context context){
        mContext = context.getApplicationContext();
    }




    @Override
    protected ArrayList<Storage.JSONDocument> doInBackground(URL... params) {
        ArrayList<Storage.JSONDocument> jsonDocList = null;
        StorageService storageService = App42API.buildStorageService();
        try {
            Storage storage = storageService.findAllDocuments(
                    Constants.CLOUD_DB_NAME, Constants.COLLECTION_NAME);
            jsonDocList = storage.getJsonDocList();

            Log.i(TAG, "Velikost databaze> " + jsonDocList.size());
            return jsonDocList;
        } catch (Exception ex){
            System.out.println("Exception Message> "+ex.getMessage());
        }
        return null;
    }


    protected void onPostExecute(ArrayList<Storage.JSONDocument> jsonDocList) {

        try {
            if (jsonDocList.isEmpty()) {} else {
            saveToDatabase(jsonDocList);
                jsonDocList.clear();}
        } catch (Exception ex){
            System.out.println("Exception Message> "+ex.getMessage());
        }
    }

    private void saveToDatabase(ArrayList<Storage.JSONDocument> jsonDocs) {
        Log.i(TAG, "saveToDatabase");
        //Log.i(TAG + " Start>", df.format(date));

        if (mContext == null){
            pomContext = mActivity;
        } else {
            pomContext = mContext;
        }
        SQLiteDatabase db = (new DatabaseHelper(pomContext)).getWritableDatabase();


        //db = DatabaseHelper.open();
        //DatabaseHelper.getInstance().open();
        ContentValues cv=new ContentValues();
        //Upgrade smaze celou tabulku!!!
        DatabaseHelper dq = new DatabaseHelper(pomContext);
        dq.onUpgrade(db, 1, 2);
    /*
        for(Storage.JSONDocument oneJsonDoc : jsonDocs) {
            cv.put(Constants.UPDATED_AT, oneJsonDoc.getUpdatedAt());
            cv.put(Constants.CREATED_AT, oneJsonDoc.getCreatedAt());
            cv.put(Constants.DOC_ID, oneJsonDoc.getDocId());
            cv.put(Constants.JSON, oneJsonDoc.getJsonDoc());
            if (oneJsonDoc.getLocation() == null) {
                Log.i(TAG, "Location NULL");
                cv.put(Constants.LATITUDE, (byte[]) null);
                cv.put(Constants.LONGITUDE, (byte[]) null);
            } else {
                cv.put(Constants.LATITUDE, oneJsonDoc.getLocation().getLat().floatValue());
                cv.put(Constants.LONGITUDE, oneJsonDoc.getLocation().getLng().floatValue());
            }
            db.insert(Constants.TABLE_NAME, Constants.JSON, cv);
            Log.i(TAG, "insert");
        }
    */

        for(int i=0;i<jsonDocs.size();i++){
            cv.put(Constants.UPDATED_AT, jsonDocs.get(i).getUpdatedAt());
            cv.put(Constants.CREATED_AT, jsonDocs.get(i).getCreatedAt());
            cv.put(Constants.DOC_ID, jsonDocs.get(i).getDocId());
            cv.put(Constants.JSON, jsonDocs.get(i).getJsonDoc());
            if (jsonDocs.get(i).getLocation() == null) {
                Log.i(TAG, "Location NULL");
                cv.put(Constants.LATITUDE, (byte[]) null);
                cv.put(Constants.LONGITUDE, (byte[]) null);
            } else {
                cv.put(Constants.LATITUDE, jsonDocs.get(i).getLocation().getLat().floatValue());
                cv.put(Constants.LONGITUDE, jsonDocs.get(i).getLocation().getLng().floatValue());
            }
            db.insert(Constants.TABLE_NAME, Constants.JSON, cv);
            Log.i(TAG, "insert");
        }

        db.close();
        dq.close();
        ReportsActivity.Log(pomContext, TAG, "Sync from cloud OK");
        Log.i(TAG, "Sync from cloud OK");
        Toast.makeText(pomContext, "Sync Done",Toast.LENGTH_SHORT).show();
        //cv.clear();
    }
}
