package com.example.patrice.job_scheduler_01;

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity
{
    public static final int JOB_ID = 1;

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

        //scheduleJob();

        if (android.os.Build.VERSION.SDK_INT >= 21 ) // android.os.Build.VERSION_CODES.LOLLIPOP
        {
            Toast.makeText(this, "Compatible", Toast.LENGTH_LONG).show();
        }
        else
        {
            Toast.makeText(this, "Trop view", Toast.LENGTH_LONG).show();
        }

        //methode1();

       // TimeUnit.HOURS.toMillis(1);

    }

    private void methode1()
    {
        ComponentName mServiceComponent = new ComponentName(this, MyJobService.class);

        JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, mServiceComponent);

        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);

        builder.setRequiresDeviceIdle(false);

        builder.setRequiresCharging(false);
/**/

 //       builder.setMinimumLatency(1 * 1000); // wait at least
 //       builder.setOverrideDeadline(3 * 1000); // maximum delay
/**/
        //1000ms = 1 second
        builder.setPeriodic(16000); // 18000 = 18 min  20000 = 20 min donc 2000 = 2min

        builder.setPersisted(true); // boot

        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(builder.build());

        Toast.makeText(this, "Job service started", Toast.LENGTH_SHORT).show();

    }

    private void scheduleJob()
    {
        ComponentName serviceName = new ComponentName(this, MyJobService.class);
        JobInfo jobInfo = new JobInfo.Builder(JOB_ID, serviceName)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                .setRequiresDeviceIdle(true)
                .setRequiresCharging(true)
//                .setOverrideDeadline(400) // Remove comment for faster testing.
                .build();

        JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        int result = scheduler.schedule(jobInfo);

        if (result == JobScheduler.RESULT_SUCCESS)
        {
            Toast.makeText(this, "Bingo", Toast.LENGTH_LONG).show();
        }
    }

}
