/*
 * Copyright (C) 2014 Simon Vig Therkildsen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.simonvt.cathode.remote.sync.shows;

import android.content.ContentProviderOperation;
import android.content.OperationApplicationException;
import android.os.RemoteException;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import net.simonvt.cathode.BuildConfig;
import net.simonvt.cathode.api.entity.ShowProgress;
import net.simonvt.cathode.api.service.ShowsService;
import net.simonvt.cathode.provider.DatabaseContract;
import net.simonvt.cathode.provider.EpisodeWrapper;
import net.simonvt.cathode.provider.ProviderSchematic;
import net.simonvt.cathode.provider.ShowWrapper;
import net.simonvt.cathode.jobqueue.Job;
import net.simonvt.cathode.jobqueue.JobFailedException;
import timber.log.Timber;

public class SyncShowWatchedStatus extends Job {

  @Inject transient ShowsService showsService;

  private long traktId;

  public SyncShowWatchedStatus(long traktId) {
    this.traktId = traktId;
  }

  @Override public String key() {
    return "SyncShowWatchedStatus" + "&traktId=" + traktId;
  }

  @Override public int getPriority() {
    return PRIORITY_4;
  }

  @Override public void perform() {
    ShowProgress progress = showsService.getWatchedProgress(traktId);
    final long showId = ShowWrapper.getShowId(getContentResolver(), traktId);

    List<ShowProgress.Season> seasons = progress.getSeasons();

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    for (ShowProgress.Season season : seasons) {
      final int seasonNumber = season.getNumber();

      List<ShowProgress.Episode> episodes = season.getEpisodes();
      for (ShowProgress.Episode episode : episodes) {
        final long episodeId =
            EpisodeWrapper.getEpisodeId(getContentResolver(), showId, seasonNumber,
                episode.getNumber());
        ContentProviderOperation.Builder builder =
            ContentProviderOperation.newUpdate(ProviderSchematic.Episodes.withId(episodeId));
        builder.withValue(DatabaseContract.EpisodeColumns.WATCHED, episode.getCompleted());
        ops.add(builder.build());
      }
    }

    try {
      getContentResolver().applyBatch(BuildConfig.PROVIDER_AUTHORITY, ops);
    } catch (RemoteException e) {
      Timber.e(e, "SyncShowWatchedStatus failed");
      throw new JobFailedException(e);
    } catch (OperationApplicationException e) {
      Timber.e(e, "SyncShowWatchedStatus failed");
      throw new JobFailedException(e);
    }
  }
}

@@ -1012,16 +1012,113 @@
 ervice;%0A
+import net.simonvt.cathode.jobqueue.Job;%0Aimport net.simonvt.cathode.jobqueue.JobFailedException;%0A
 import n
@@ -1307,19 +1307,21 @@
 ovider.S
-how
+eason
 Wrapper;
@@ -1352,76 +1352,28 @@
 ode.
-jobqueue.Job;%0Aimport net.simonvt.cathode.jobqueue.JobFailedException
+provider.ShowWrapper
 ;%0Aim
@@ -1872,30 +1872,24 @@
 aktId);%0A    
-final 
 long showId 
@@ -1943,16 +1943,153 @@
 raktId);
+%0A    if (showId == -1L) %7B%0A      showId = ShowWrapper.createShow(getContentResolver(), traktId);%0A      queue(new SyncShow(traktId));%0A    %7D
 %0A%0A    Li
@@ -2471,16 +2471,65 @@
   final 
+int episodeNumber = episode.getNumber();%0A        
 long epi
@@ -2624,46 +2624,483 @@
 ber,
-%0A                episode.getNumber());
+ episodeNumber);%0A%0A        if (episodeId == -1L) %7B%0A          long seasonId = SeasonWrapper.getSeasonId(getContentResolver(), showId, seasonNumber);%0A          if (seasonId == -1L) %7B%0A            seasonId = SeasonWrapper.createSeason(getContentResolver(), showId, seasonNumber);%0A          %7D%0A%0A          episodeId =%0A              EpisodeWrapper.createEpisode(getContentResolver(), showId, seasonId, episodeNumber);%0A          queue(new SyncSeason(traktId, seasonNumber));%0A        %7D%0A
 %0A   

Create episode if it doesn't exist.