package com.lemenzo.clock.stopwatch;
import android.content.*;import android.os.SystemClock;import org.json.*;import java.util.*;
public final class StopwatchRepository{
 private final SharedPreferences p;
 public StopwatchRepository(Context c){p=c.createDeviceProtectedStorageContext().getSharedPreferences("stopwatch",0);}
 public boolean running(){return p.getBoolean("running",false);}public long started(){return p.getLong("started",0);}public long accumulated(){return p.getLong("accum",0);}private long startedWall(){return p.getLong("started_wall",0);}
 public synchronized long elapsed(){long base=accumulated();if(!running())return Math.max(0,base);long nowElapsed=SystemClock.elapsedRealtime(),startElapsed=started();if(startElapsed>0&&nowElapsed>=startElapsed)return Math.max(0,base+(nowElapsed-startElapsed));long wall=startedWall(),delta=wall>0?Math.max(0,System.currentTimeMillis()-wall):0;long normalized=base+delta;p.edit().putLong("accum",normalized).putLong("started",nowElapsed).putLong("started_wall",System.currentTimeMillis()).apply();return normalized;}
 public void start(){if(!running())p.edit().putBoolean("running",true).putLong("started",SystemClock.elapsedRealtime()).putLong("started_wall",System.currentTimeMillis()).apply();}
 public void pause(){if(running())p.edit().putLong("accum",elapsed()).putBoolean("running",false).remove("started").remove("started_wall").apply();}
 public void reset(){p.edit().clear().apply();}
 public List<Long> laps(){ArrayList<Long>o=new ArrayList<>();try{JSONArray a=new JSONArray(p.getString("laps","[]"));for(int i=0;i<a.length();i++)o.add(a.getLong(i));}catch(Exception ignored){}return o;}
 public void lap(){List<Long>a=laps();a.add(elapsed());JSONArray j=new JSONArray();for(long v:a)j.put(v);p.edit().putString("laps",j.toString()).apply();}
}