package com.hyperling.apps.wheretheriverfrowns;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import java.util.Date;

/**
 * Created by ling on 10/2/16.
 */

public class MyService extends IntentService {

    private String sharedPreferencesKey, topArticleKey, checkForNewArticlesKey, debugKey, lastServiceRunKey, nextServiceRunKey,
            TAG,
            url;

    private SharedPreferences sharedPreferences;

    private PowerManager.WakeLock wakeLock;

    private AlarmManager alarmManager;
    private PendingIntent reschedule;

    private boolean DEBUG;

    public MyService(){
        super("MyService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // Keys
        sharedPreferencesKey = getString(R.string.sharedPreferencesKey);
        topArticleKey = getString(R.string.topArticleKey);
        checkForNewArticlesKey = getString(R.string.checkForNewArticlesKey);
        debugKey = getString(R.string.debugKey);
        lastServiceRunKey = getString(R.string.lastServiceRunKey);
        nextServiceRunKey = getString(R.string.nextServiceRunKey);

        // Strings
        TAG = getString(R.string.TAG);
        url = getString(R.string.allStories);

        // Preferences
        sharedPreferences = getSharedPreferences(sharedPreferencesKey, MODE_PRIVATE);
        DEBUG = sharedPreferences.getBoolean(debugKey, false);

        // Wake Lock
        wakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        wakeLock.acquire();

        if (DEBUG) Log.d(TAG, "MyService:  Service started.");

        // Check if we have a connection
        NetworkInfo info = ((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info == null || !info.isConnected() || info.isRoaming()){
            if (DEBUG) Log.d(TAG, "MyService:  Not polling due to network.");
            rescheduleService(1);
            stopSelf();
            return;
        }

        if (sharedPreferences.getBoolean(checkForNewArticlesKey, true)) {
            wakeLock.acquire();
            WebPage webPage = new WebPage(this, url);
            if (!webPage.getTitles().isEmpty()) {
                String newTopArticle = webPage.getTitles().get(0);
                String newDate = webPage.getDates().get(0);

                String lastTopArticle = sharedPreferences.getString("TopArticle", newTopArticle);

                if (DEBUG){
                    Log.d(TAG, "MyService:  lastTopArticle=" + lastTopArticle);
                    Log.d(TAG, "MyService:  newTopArticle=" + newTopArticle);
                }

                if (!newTopArticle.equals(lastTopArticle)) {
                    createNotification(newDate, newTopArticle);
                } else {
                    rescheduleService(1);
                }

                // Release lock and resources
                wakeLock.release();
                stopSelf();
            }
        }
    }

    private void createNotification(String articleDate, String articleTitle){
        if (DEBUG){
            Log.d(TAG, "MyService:  createNotification");
        }

        // Create notification
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.wtrf_anarchy)
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setContentTitle(getResources().getString(R.string.newArticleNotificationTitle) + " - " + articleDate)
                .setContentText(articleTitle)
                .setAutoCancel(true);

        // Link so the notification opens WTRF
        Intent notificationLink = new Intent(this, MainActivity.class);
        notificationLink.setAction("");

        // Allow using back to leave app
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(notificationLink);
        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        // Add it all to the notification
        notificationBuilder.setContentIntent(pendingIntent);

        // Display notification
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(TAG, 0, notificationBuilder.build());
    }

    private void rescheduleService(int hours){
        // Schedule next run after an hour or so
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        reschedule = PendingIntent.getBroadcast(this, 0, new Intent("com.hyperling.wheretheriverfrowns.ALARM_STARTED"), 0);

        long convertedHours = 1000*60*60*hours;

        long currentTime = System.currentTimeMillis();

        alarmManager.cancel(reschedule);
        alarmManager.set(AlarmManager.RTC_WAKEUP, currentTime + convertedHours, reschedule);

        if (DEBUG) {
            Log.d(TAG, "MyService: rescheduleService:  Rescheduled for " + hours + " hour(s).");
            Log.d(TAG, "MyService: rescheduleService:  Current time= " + currentTime + ", reschedule time=" + currentTime + convertedHours);

            Date date = new Date();
            String prettyDate;
            SharedPreferences.Editor editor = sharedPreferences.edit();

            date.setTime(currentTime);
            prettyDate = date.toString();
            editor.putString(lastServiceRunKey, prettyDate);

            date.setTime(currentTime + convertedHours);
            prettyDate = date.toString();
            editor.putString(nextServiceRunKey, prettyDate);

            editor.apply();

        }
    }
}
