package dp.mendelu.roman.diplomkaapp42;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.shephertz.app42.paas.sdk.android.App42API;
import com.shephertz.app42.paas.sdk.android.App42CallBack;
import com.shephertz.app42.paas.sdk.android.storage.GeoTag;
import com.shephertz.app42.paas.sdk.android.storage.Storage;
import com.shephertz.app42.paas.sdk.android.storage.StorageService;
import com.shephertz.app42.paas.sdk.android.user.User;
import com.shephertz.app42.paas.sdk.android.user.UserService;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;

/**
 * Aktivita pro testovani/ladeni, v aplikaci nevyuzita
 */
public class CloudTransferActivity extends AppCompatActivity{
    TextView controlCloudText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cloud_transfer);
        controlCloudText = (TextView)findViewById(R.id.controlCloudText);
        controlCloudText.setText("Neco");


        //initApi(); init v mainu uz
        //getAllUsersFromCloud();
        //new AsyncLoad(this).execute();
        new AsyncLoadJSONDoc(this).execute();
    }

    /**
     * Inicializace API
     */
    public void initApi (){
        if (App42API.isInAppEnabled){
            Log.i("Init: ", "Api uz inicializovano");
        } else {
            App42API.initialize(getBaseContext(), Constants.API_KEY, Constants.SECRET_KEY);
            Log.i("Init: ", "Api zavedeno");
        }
    }

    private void getAllUsersFromCloud(){
        final UserService userService = App42API.buildUserService();

        userService.getAllUsers(new App42CallBack() {
            @Override
            public void onSuccess(Object o) {
                ArrayList<User> listUsers = new ArrayList<>();
                for (User object : userService.getAllUsers()){
                    listUsers.add(object);
                    Log.v("AllUsers: ", object.getUserName() + " " + object.getEmail() + " " + object.getSessionId());
                }
            }

            @Override
            public void onException(Exception ex) {
                Log.i("Exception Message", "" + ex.getMessage());
            }
        });
    }

    /**
     * logika s file
     */
    public void playFile(){
        /*
        Button button = (Button)findViewById(R.id.button);
        TextView textView = (TextView)findViewById(R.id.textView);
        textView.setMovementMethod(new ScrollingMovementMethod());

        FileOutputStream fOut = null;
        try {
            fOut = openFileOutput("file.txt", MODE_APPEND);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        initApi();
        insertJson("diplomka", "test", "{\"name\":\"Nick\",\"age\":30,\"phone\":\"xxx-xxx-xxx\"}");
        insertUser("Nick", "heslo", "nick@shephertz.co.in");


        for (int i=10; i<10; i++){
            insertJson("diplomka", "test", "{\"name\":\"Nick\",\"age\":3" + i +",\"phone\":\"xxx-xxx-xxx\"}");
            insertUser("Nick" + i, "heslo", "nick@shephertz.co.in");
        }

        try {
            textView.setText(loadData());
        } catch (IOException e) {
            e.printStackTrace();
        }
        */
    }

    /**
     * Vlozeni uzivatele
     *
     * @param userName
     * @param pwd
     * @param emailId
     */
    private void insertUser(String userName, String pwd, String emailId) {
        UserService userService = App42API.buildUserService();
        userService.createUser(userName, pwd, emailId, new App42CallBack() {
            public void onSuccess(Object response) {
                User user = (User) response;
                Log.i("userName is ", "" + user.getUserName());
                Log.i("emailId is ", "" + user.getEmail());
            }

            public void onException(Exception ex) {
                Log.i("Exception Message", "" + ex.getMessage());
            }
        });
    }

    /**
     * Insert Json data.
     *
     * @param dbName
     * @param collectionName
     * @param json
     */
    public void insertJson(String dbName, String collectionName, String json) {
        GeoTag gp = new GeoTag();
        gp.setLat(new BigDecimal(-73.99171));
        gp.setLng(new BigDecimal(40.738868));

        StorageService storageService = App42API.buildStorageService();
        storageService.setGeoTag(gp);
        storageService.insertJSONDocument(dbName, collectionName, json, new App42CallBack() {
            public void onSuccess(Object response) {
                Storage storage = (Storage) response;
                Log.i("dbName is ", "" + storage.getDbName());
                Log.i("collection Name is ", "" + storage.getCollectionName());
                ArrayList<Storage.JSONDocument> jsonDocList = storage.getJsonDocList();
                for (int i = 0; i < jsonDocList.size(); i++) {
                    Log.i("objectId is ", "" + jsonDocList.get(i).getDocId());
                    Log.i("CreatedAt is ", "" + jsonDocList.get(i).getCreatedAt());
                    Log.i("UpdatedAtis ", "" + jsonDocList.get(i).getUpdatedAt());
                    Log.i("Jsondoc is ", "" + jsonDocList.get(i).getJsonDoc());
                }
            }

            public void onException(Exception ex) {
                Log.i("Exception Message", "" + ex.getMessage());
            }
        });
    }

    public void setMeAllData(String data) throws IOException {
        FileOutputStream fOut = openFileOutput("file1.txt", MODE_APPEND);
        data = data + " \n";
        fOut.write(data.getBytes());
        fOut.close();
    }

    public void queryData(View v){
        String dbName = "diplomka";
        String collectionName = "test";
        StorageService storageService = App42API.buildStorageService();
        storageService.findAllDocuments(dbName, collectionName, new App42CallBack() {
            public void onSuccess(Object response) {
                Storage storage = (Storage) response;
                Log.i("dbName is ", "" + storage.getDbName());
                Log.i("collection Name is ", "" + storage.getCollectionName());
                ArrayList<Storage.JSONDocument> jsonDocList = storage.getJsonDocList();

                try {
                    allJsonData(jsonDocList);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


            public void onException(Exception ex) {
                Log.i("Exception Message", "" + ex.getMessage());
            }

        });

    }

    private void allJsonData(ArrayList<Storage.JSONDocument> jsonDocList) throws IOException {
        FileOutputStream fOut = openFileOutput("file1.txt", MODE_APPEND);
        for(Storage.JSONDocument oneJsonDocList : jsonDocList){
            String pom = "";
            pom = pom + "" + oneJsonDocList.getDocId().toString() +
                    oneJsonDocList.getCreatedAt().toString() +
                    oneJsonDocList.getUpdatedAt().toString() +
                    oneJsonDocList.getJsonDoc().toString();
            fOut.write(pom.getBytes());
        }
        fOut.close();
    }

    public String loadData() throws IOException {
        FileInputStream fin = openFileInput("file1.txt");
        int c;
        String temp="";

        while ( (c = fin.read()) != -1) {
            //Log.v("fin.read()", fin.read() + "");
            //pozor na takovou kontrolu, nacita dalsi znak a kazi vystup
            temp = temp + Character.toString((char)c);
        }

        return temp;
    }

}
