package ctbrec.sites.showup;

import static ctbrec.io.HttpConstants.*;

import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iheartradio.m3u8.ParseException;
import com.iheartradio.m3u8.PlaylistException;

import ctbrec.Config;
import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import ctbrec.recorder.download.hls.MergedFfmpegHlsDownload;
import okhttp3.Request;
import okhttp3.Response;

public class ShowupMergedDownload extends MergedFfmpegHlsDownload {

    private static final Logger LOG = LoggerFactory.getLogger(ShowupMergedDownload.class);

    public ShowupMergedDownload(HttpClient client) {
        super(client);
    }

    @Override
    protected void downloadSegments(String segmentPlaylistUri, boolean livestreamDownload) throws IOException, ParseException, PlaylistException {
        try {
            SegmentPlaylist lsp = getNextSegments(segmentPlaylistUri);
            emptyPlaylistCheck(lsp);

            for (String segment : lsp.segments) {
                Request request = new Request.Builder().url(segment)
                        .header(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                        .header(CONNECTION, KEEP_ALIVE)
                        .build();
                try (Response response = client.execute(request)) {
                    if (response.isSuccessful()) {
                        InputStream in = response.body().byteStream();
                        byte[] buffer = new byte[10240];
                        int length = -1;
                        boolean keepGoing = true;
                        while ((length = in.read(buffer)) >= 0 && keepGoing) {
                            writeSegment(buffer, 0, length);
                            keepGoing = running && !Thread.interrupted() && model.isOnline(true);
                            if (livestreamDownload && splitRecording()) {
                                break;
                            }
                        }
                    } else {
                        throw new HttpException(response.code(), response.message());
                    }
                }
            }
        } catch (HttpException e) {
            if (e.getResponseCode() == 404) {
                LOG.debug("Playlist not found (404). Model {} probably went offline", model);
            } else if (e.getResponseCode() == 403) {
                LOG.debug("Playlist access forbidden (403). Model {} probably went private or offline", model);
            } else {
                LOG.info("Unexpected error while downloading {}", model, e);
            }
            running = false;
        } catch (Exception e) {
            LOG.info("Unexpected error while downloading {}", model, e);
            running = false;
        }

        ffmpegThread.interrupt();
    }
}
