package com.application.tak.takapplication.services;


import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.RemoteViews;

import com.application.tak.takapplication.R;
import com.application.tak.takapplication.actClientTask;
import com.application.tak.takapplication.actStudentTask;
import com.application.tak.takapplication.actWelcomeScrean;
import com.application.tak.takapplication.data_access.Config;
import com.application.tak.takapplication.data_access.GetAllClientTasks;
import com.application.tak.takapplication.data_access.GetAllClientTasksByStatus;
import com.application.tak.takapplication.data_access.GetAllStudentTasks;
import com.application.tak.takapplication.data_model.Task_V;
import com.application.tak.takapplication.data_model.User;
import com.application.tak.takapplication.interfaces.OnDBRequestFinished;
import com.application.tak.takapplication.local_db.LocalDB;

import java.util.ArrayList;
import java.util.List;

public class BackgroundService extends Service {

    public BackgroundService()
    {
      //  ctx = getApplicationContext();
    }

    public static final String SERVICE_RESULT = "abc";
    LocalBroadcastManager broadcastMgr;
    NotificationManager mNotificationManager;
    GetAllClientTasksByStatus data;
    GetAllStudentTasks dataStudent;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        broadcastMgr = LocalBroadcastManager.getInstance(this);
    }

   public void sendResultForClient(User u) {

        data = new GetAllClientTasksByStatus(getApplicationContext(),u,2);

        data.setDBRequestFinishedListener(new OnDBRequestFinished() {
            @Override
            public void onDBRequestFinished() {
                if(data._tasks != null)
                {
                    Intent intent = new Intent(SERVICE_RESULT);
                    boolean sendNotification = false;
                    for(Task_V t : data._tasks)
                    {
                        if((t.get_IsClientNotifyRead() == null || t.get_IsClientNotifyRead() == 0) && t.get_ExecutorId() != null && t.get_ExecutorId() != 0)
                        {
                            sendNotification = true;
                        }


                    }
                    if(sendNotification)
                    {
                        sendNotification = false;
                        broadcastMgr.sendBroadcast(intent);

                        addNotificationForClient();
                    }
                }
            }
        });

    }


    public void sendResultForStudent(User u) {

        LocalDB local = new LocalDB(getApplicationContext());
        List<Integer> tasks = local.GetNotificationsForUser(u.get_Id());

        dataStudent = new GetAllStudentTasks(getApplicationContext(),u);

        dataStudent.setDBRequestFinishedListener(new OnDBRequestFinished() {
            @Override
            public void onDBRequestFinished() {
                if(dataStudent._tasks != null)
                {
                    Intent intent = new Intent(SERVICE_RESULT);
                    boolean sendNotification = false;
                    for(Task_V t : dataStudent._tasks)
                    {
                        if(t.get_StatusId() == 1)
                        {
                            boolean isFound = false;
                        for(Integer i : tasks)
                        {
                            if(t.get_Id().equals(i))
                            {

                                isFound = true;

                            }
                        }

                        if(!isFound)
                        {
                            sendNotification = true;
                            isFound = false;
                        }
                        }


                    }
                    if(sendNotification)
                    {
                        sendNotification = false;
                        broadcastMgr.sendBroadcast(intent);
                        addNotificationForStudent();
                    }
                }
            }
        });

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {

        LoginStatus logStatus = new LoginStatus(getApplicationContext());
        User u =logStatus.IsLoggedIn();
        if(u != null && u.get_RoleId() == 2)
        {
            sendResultForClient(u);
        }
        else if(u!= null && u.get_RoleId() == 1)
        {
            sendResultForStudent(u);
        }


        stopSelf();
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        //restart
        AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);

        //co 10 minut
        alarm.set(
                alarm.RTC_WAKEUP,
                System.currentTimeMillis() + (1000 * 300),//600
                PendingIntent.getService(this, 0, new Intent(this, BackgroundService.class), 0)
        );
    }

    private void addNotificationForStudent() {

        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, actWelcomeScrean.class), 0);


        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.logo)
                .setContentTitle("TAK!")
                .setContentText("Ktoś potrzebuje Twojej pomocy!")
                .setContentIntent(pi)
                .setAutoCancel(true)
                .setSound(alarmSound)
                .build();

        mNotificationManager.notify(0,notification);
    }

    private void addNotificationForClient() {

        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, actWelcomeScrean.class), 0);


        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.logo)
                .setContentTitle("TAK!")
                .setContentText("Ktoś zdecydował się Ci pomóc!")
                .setContentIntent(pi)
                .setAutoCancel(true)
                .setSound(alarmSound)
                .build();

        mNotificationManager.notify(0,notification);
    }
}
