package dp.mendelu.roman.diplomkaapp42;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
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.App42Exception;
import com.shephertz.app42.paas.sdk.android.App42BadParameterException;
import com.shephertz.app42.paas.sdk.android.App42NotFoundException;
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.User.Profile;
import com.shephertz.app42.paas.sdk.android.user.User.UserGender;
import com.shephertz.app42.paas.sdk.android.user.UserService;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import static android.widget.TextView.*;

/**
 * Spousteci aktivita. Slouzi jako uzivatelske rozhrani v aplikaci.
 */
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    SyncServiceApp mService;
    boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initApi();

        //start sluzby
        startSyncService();

            //synchronizace celeho cloudu do lokal. db
            //new AsyncLoadJSONDoc(this).execute();

        /*
        try {
            parse();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        */
    }

    /**
     * Inicializace API
     */
    public void initApi (){
        App42API.initialize(getBaseContext(), Constants.API_KEY, Constants.SECRET_KEY);
    }

    public void startSyncService(){
        Intent intent = new Intent(this, SyncServiceApp.class);
        startService(intent);
    }

    public void startCreate(View view){
        Intent intent = new Intent(this, CreatePointActivity.class);
        startActivity(intent);
    }

    public void startList(View view){
        Intent intent = new Intent(this, ListActivity.class);
        startActivity(intent);
    }

    public void startReports(View view){
        Intent intent = new Intent(this, ReportsActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(this, SyncServiceApp.class);
        stopService(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent i;
        switch (item.getItemId()) {
            case R.id.startCloud:
                new AsyncLoadJSONDoc(this).execute();
                Log.i(TAG, "Syncing to cloud");
                Toast.makeText(this, "Syncing to cloud",Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Algoritmus pro porovnani casovych razitek.
     * @throws ParseException
     */
    void parse() throws ParseException {
        String updatedAt = "2015-12-23T01:41:40.437Z";
        String updatedAt2 = "2014-12-23T01:41:40.437Z";
        String updatedAt3 = "2015-12-23T01:41:45.437Z";
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSS'Z'");

        Date result2 = df.parse(updatedAt2);
        Date result3 = df.parse(updatedAt3);
        Date result = df.parse(updatedAt);
        Log.i(TAG, result + "");

        if(result.compareTo(result2)>0){
            System.out.println("Date1 is after Date2");
        }else if(result.compareTo(result2)<0){
            System.out.println("Date1 is before Date2");
        }else if(result.compareTo(result2)==0){
            System.out.println("Date1 is equal to Date2");
        }else{
            System.out.println("How to get here?");
        }

        if(result.compareTo(result3)>0){
            System.out.println("Date1 is after Date2");
        }else if(result.compareTo(result3)<0){
            System.out.println("Date1 is before Date2");
        }else if(result.compareTo(result3)==0){
            System.out.println("Date1 is equal to Date2");
        }else{
            System.out.println("How to get here?");
        }

    }

    /**
     * logika s file, testovaci metoda
     */
    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;
                System.out.println("userName is " + user.getUserName());
                System.out.println("emailId is " + user.getEmail());
            }

            public void onException(Exception ex) {
                System.out.println("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;
                System.out.println("dbName is " + storage.getDbName());
                System.out.println("collection Name is " + storage.getCollectionName());
                ArrayList<Storage.JSONDocument> jsonDocList = storage.getJsonDocList();
                for (int i = 0; i < jsonDocList.size(); i++) {
                    System.out.println("objectId is " + jsonDocList.get(i).getDocId());
                    System.out.println("CreatedAt is " + jsonDocList.get(i).getCreatedAt());
                    System.out.println("UpdatedAtis " + jsonDocList.get(i).getUpdatedAt());
                    System.out.println("Jsondoc is " + jsonDocList.get(i).getJsonDoc());
                }
            }

            public void onException(Exception ex) {
                System.out.println("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;
                System.out.println("dbName is " + storage.getDbName());
                System.out.println("collection Name is " + storage.getCollectionName());
                ArrayList<Storage.JSONDocument> jsonDocList = storage.getJsonDocList();

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


            public void onException(Exception ex) {
                System.out.println("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;
    }
}

