package com.jkanetwork.st.calendariodefrases;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.marcohc.robotocalendar.RobotoCalendarView.RobotoCalendarListener;
import com.marcohc.robotocalendar.RobotoCalendarView;

import java.text.DateFormatSymbols;
import java.util.Calendar;


public class MainActivity extends AppCompatActivity implements RobotoCalendarListener {

    private RobotoCalendarView robotoCalendarView;
    DatabaseHelper db = new DatabaseHelper(this);
    Calendar cal = Calendar.getInstance();
    Integer IDFrase;
    final Config conf = new Config(this);

    /* Will use when move month back and forth, because library doesnt show the actual month.. */
    Integer calMonth = cal.get(Calendar.MONTH)+1; //From 1 to 12, and not from 0 to 11
    Integer calYear = cal.get(Calendar.YEAR);

    /* Texts making all activity used, and valued in onCreate */
    TextView txtfraseTitle;
    TextView txtfraseText;
    TextView txtfraseAutor;


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.favorites:
                Intent newIF= new Intent(MainActivity.this,FavsActivity.class);
                startActivity(newIF);
                return true;
            case R.id.options:
                Intent newIO= new Intent(MainActivity.this,OptsActivity.class);
                startActivity(newIO);
                return true;
            case R.id.about:
                Intent newIA= new Intent(MainActivity.this,AboutOfActivity.class);
                startActivity(newIA);
                return true;
            case R.id.exit:
                moveTaskToBack(true); /* Returns to "desktop" */
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /* First of all,before loading, see if its the first time using the app */
        if (conf.getFirstTime()){
            Intent newFA= new Intent(MainActivity.this,FirstStartActivity.class);
            startActivity(newFA);
        }

        setContentView(R.layout.activity_main);
        txtfraseTitle = (TextView) findViewById(R.id.txt_frasetitle);
        txtfraseText = (TextView) findViewById(R.id.txt_frasetext);
        txtfraseAutor = (TextView) findViewById(R.id.txt_fraseautor);

        /* Calendar basic settings */
        robotoCalendarView = (RobotoCalendarView) findViewById(R.id.calendarPicker);
        robotoCalendarView.setRobotoCalendarListener(this);
        robotoCalendarView.setShortWeekDays(false);
        robotoCalendarView.showDateTitle(true);

        /* Admob ads */
        MobileAds.initialize(getApplicationContext(), MainActivity.this.getString(R.string.admob_launch_api));
        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        onResume(); /* Here all that as to be refreshed when app opens from background */


        /* Configure alarm */
        Alarm alarm = new Alarm();
        alarm.putAlarm(this);

        /* Register context menu */
        registerForContextMenu(txtfraseText);
    }

    @Override
    public void onResume(){
        super.onResume();
        /* Refresh calendar */
        cal = Calendar.getInstance();
        calMonth = cal.get(Calendar.MONTH)+1; //From 1 to 12, and not from 0 to 11
        calYear = cal.get(Calendar.YEAR);


        //Load today's sentence and set texts
        IDFrase = db.getIDFraseHoy();

        /* Refresh calendar, after load sentences for checks */
        robotoCalendarView.updateView();
        markDates();

        txtfraseText.setText(db.getFraseFromID(IDFrase));
        txtfraseAutor.setText(db.getAutorFromID(IDFrase));


        // ListView Item Click Listener
        txtfraseText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View viewIn) {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setPrimaryClip(ClipData.newPlainText("Sentence", txtfraseText.getText()+MainActivity.this.getString(R.string.sharefrom)));
                Toast.makeText(getApplicationContext(), "Copiado al portapapeles", Toast.LENGTH_LONG ).show();
            }
        });
    }


    /* Close app on back button */
    @Override
    public void onBackPressed()
    {
        moveTaskToBack(true);
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.proverbmenu_add, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        TextView txtfraseText = (TextView) findViewById(R.id.txt_frasetext);
        String sentence = txtfraseText.getText().toString();
        switch (item.getItemId()) {
            case R.id.copy:
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setPrimaryClip(ClipData.newPlainText("Sentence", sentence+MainActivity.this.getString(R.string.sharefrom)));
                Toast.makeText(getApplicationContext(), "Copiado al portapapeles", Toast.LENGTH_LONG ).show();
                return true;
            case R.id.addfav:
                db.addFav(IDFrase);
                return true;
            case R.id.share:
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, sentence+MainActivity.this.getString(R.string.sharefrom));
                startActivity(Intent.createChooser(intent, "Compartir con"));
                return true;
        }
        return false;
    }


    @Override
    public void onDayClick(Calendar daySelectedCalendar) {
        Integer month = daySelectedCalendar.get(Calendar.MONTH);
        Integer day = daySelectedCalendar.get(Calendar.DAY_OF_MONTH);
        Integer year = daySelectedCalendar.get(Calendar.YEAR);
        month=month+1; //Now months start with 1 and not 0
                /* Load sentence */
        IDFrase = db.getIDFraseDay(year, month, day);
        String frase = db.getFraseFromID(IDFrase);
        txtfraseText.setText(frase); //Change text
        txtfraseAutor.setText(db.getAutorFromID(IDFrase));
                /* Set Title before sentence */
        if (year != cal.get(Calendar.YEAR) || month != (cal.get(Calendar.MONTH)+1) || day != cal.get(Calendar.DAY_OF_MONTH)) {
            txtfraseTitle.setText("Frase del " + day + " de " + getMonth(month)); //Change title
        }else {
            txtfraseTitle.setText(R.string.txt_todaysentence); //Change title (today)
        }
        //markDates(); TODO El programa borra el día seleccionado al hacerlo
    }

    /** It returns the month name */
    public String getMonth(int month) {
        String str = new DateFormatSymbols().getMonths()[month-1];
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    @Override
    public void onDayLongClick(Calendar daySelectedCalendar) {
        onDayClick(daySelectedCalendar);
    }

    public void markDates() {
        robotoCalendarView.clearCalendar();

        Calendar time = Calendar.getInstance();
        String[] IDDays = db.getAllDaysYet();
        if (IDDays.length != 0) {
            for (int x = 0; x <= IDDays.length - 1; x++) {
                //Log.d("Date", "String: " + String.valueOf(IDDays[x]));
                Integer year = Integer.parseInt(IDDays[x].substring(0, 4));
                Integer month = Integer.parseInt(IDDays[x].substring(4, 6));
                Integer day = Integer.parseInt(IDDays[x].substring(6, 8));
                if (year.equals(calYear) && month.equals(calMonth)) {
                    time.set(Calendar.DAY_OF_MONTH, day);
                    time.set(Calendar.MONTH, month-1);
                    //Log.d("Date", "Marking: " + day);
                    robotoCalendarView.markCircleImage1(time);
                }
            }
        }
    }

    /* Overrides for month plus and minus */
    @Override
    public void onRightButtonClick() {
        calMonth += 1;
        if (calMonth > 12){
            calMonth = 1;
            calYear += 1;
        }
        markDates();
    }

    @Override
    public void onLeftButtonClick() {
        calMonth -= 1;
        if (calMonth < 1){
            calMonth = 12;
            calYear -= 1;
        }
        markDates();
    }
}