package com.mydrivesolutions.androidtechtalksapril.ui.activity;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.mydrivesolutions.androidtechtalksapril.R;
import com.mydrivesolutions.androidtechtalksapril.rest.model.GitHubOwner;
import com.mydrivesolutions.androidtechtalksapril.rest.model.GitHubRepo;
import com.mydrivesolutions.androidtechtalksapril.ui.adapter.RealmAdapter;

import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.realm.Realm;
import io.realm.RealmResults;

public class RealmActivity extends AppCompatActivity {

    @BindView(R.id.realm__activity_list)
    RecyclerView recyclerView;

    private Realm realm;
    private RealmAdapter realmAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_realm);

        ButterKnife.bind(this);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);

        realmAdapter = new RealmAdapter();

        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(realmAdapter);
        recyclerView.setLayoutManager(layoutManager);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(view -> {

        });
    }

    private void createData() {
        Toast.makeText(getApplicationContext(), "Creating 20 usres...", Toast.LENGTH_SHORT).show();
        GitHubRepo repo;
        GitHubOwner owner;
        realm.beginTransaction();
        for (int i = 0; i < 20; i++) {
            repo = realm.createObject(GitHubRepo.class);
            owner = realm.createObject(GitHubOwner.class);
            owner.setLogin(String.format(Locale.ENGLISH, "User %s", i));
            repo.setGitHubOwner(owner);
            realm.copyToRealm(owner);
        }
        realm.commitTransaction();
    }

    private void displayData() {
        Toast.makeText(getApplicationContext(), "Displaying ...", Toast.LENGTH_SHORT).show();
        RealmResults<GitHubRepo> owners = realm.where(GitHubRepo.class).findAll();
        realmAdapter.setRepoList(owners);
    }

    @Override
    public void onResume() {
        super.onResume();
        realm = Realm.getDefaultInstance();
        createData();
        displayData();
    }

    @Override
    public void onPause() {
        super.onPause();
        realm.close();
    }
}
