package dp.mendelu.roman.diplomkaapp42;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.shephertz.app42.paas.sdk.android.storage.Storage;

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

/**
 * Aktivita pro sber informaci tykajici se synchronizce mezi cloudem a lok. databazi
 * Reporty vsech akci uzivatele. Ulozeny z vypisovany z lok. databaze.
 */
public class ReportsActivity extends android.app.ListActivity {
    private final String TAG = "ReportsActivity";
    private SQLiteDatabase db=null;
    private Cursor mCursor=null;
    private String columns[] = new String[]{"_id", "tag", "log", "time"};

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_reports); //nesmi byt u ListActivity, pada na null

        db = (new DbHelp(this)).getWritableDatabase();

        //smaze databazi a vyvori novou
        //DbHelp dq = new DbHelp(this);
        //dq.onUpgrade(db,1,2);

        //mCursor = db.rawQuery("SELECT _ID, layer, latitude, longitude, project" +
        //        " FROM geometry ORDER BY _ID", null);

        //mCursor = getContentResolver().query(Uri.parse("content://dp.mendelu.roman.diplomkaapp42/geometry"), );

        mCursor = db.query(Constants.TABLE_NAME_REPORTS, columns, null, null, null, null, "time");
        /**
         * Kontrola sql dotazu
         */
        mCursor.moveToFirst();
        while (!mCursor.isAfterLast()){
            String id = mCursor.getString(0);
            String tag = mCursor.getString(1);
            String log = mCursor.getString(2);
            String time = mCursor.getString(3);

            Log.i(TAG, id + tag + log + time);
            mCursor.moveToNext();

        }

        /*ListAdapter adapter = new SimpleCursorAdapter(this,
                R.layout.row, this.mCursor,
                new String[] {"_id","layer", "project", "latitude", "longitude"},
                new int[] {R.id.idecko, R.id.layer, R.id.project, R.id.latitude, R.id.longitude});

        setListAdapter(adapter);
        registerForContextMenu(getListView());
        */
        CursorAdapter mCursorAdapter = null;
        mCursorAdapter = new SimpleCursorAdapter(
                getApplicationContext(),
                R.layout.row2,
                mCursor,
                columns,
                new int[]{R.id.textViewId, R.id.textViewTag, R.id.textViewInfo, R.id.textViewTime},
                0);

        setListAdapter(mCursorAdapter);
        registerForContextMenu(getListView());

        ListView lv;
        lv = getListView();
        /*
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mCursor.moveToPosition(position); //nastavim pozici kliknuteho radku
                Log.i("position", position + "");
                Log.i("id", "" + id);
                Intent intent = new Intent(getApplicationContext(), DetailJSONActivity.class);
                intent.putExtra("id", mCursor.getString(0)); //predavam ID
                intent.putExtra("json", mCursor.getString(4)); // posilam stringovej json

                Log.i("id v sql", mCursor.getString(0));
                //Log.i("sql json", mCursor.getString(4)); // pokud null, spadne, osetreno az v detailu

                startActivity(intent);
            }
        });*/
        db.close();

    }

    public static void Log(Context context, String tag, String log){
        saveToDatabase(context,tag,log);
    }

    private static void saveToDatabase(Context context, String tag, String log) {
        SQLiteDatabase db = (new DbHelp(context)).getWritableDatabase();
        ContentValues cv=new ContentValues();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSS'Z'");
        Date date = new Date();

        cv.put(Constants.DB_TAG, tag);
        cv.put(Constants.LOG, log);
        cv.put(Constants.TIME, df.format(date));
        db.insert(Constants.TABLE_NAME_REPORTS, Constants.TIME, cv);

        db.close();
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent i;
        switch (item.getItemId()) {
            case R.id.delReports:
                DbHelp dq = new DbHelp(this);
                dq.onUpgrade(db,1,2);
                recreate();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mCursor.close();
        db.close();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        recreate();
        Toast.makeText(this,"Refreshing list", Toast.LENGTH_SHORT).show();
    }
}

