package org.wyrez.shootingstars.data;

/*
 * Copyright (C) 2013 Darth Affe <http://wyrez.org> and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import com.github.axet.vget.VGet;
import com.github.axet.vget.info.VideoInfo;
import com.github.axet.vget.info.VideoInfo.VideoQuality;
import java.io.File;
import java.net.URL;

/**
 *
 * @author Darth Affe
 */
public class YTDownloader {

    private File lastTarget;

    public YTDownloader() {
    }

    public boolean download(String source, String targetFolder) {
        System.out.println("downloading " + source);
        boolean first = true;
        boolean process = true;
        VideoInfo info = null;

        while (process) {
            try {
                if (first) {
                    info = new VideoInfo(new URL(source));
                    info.setUserQuality(VideoQuality.p720);
                    info.setVideoQuality(VideoQuality.p720);
                }
                VGet v = new VGet(info, new File(targetFolder));
                v.download();
                lastTarget = v.getTarget();
                System.out.println("success!");
                return true;
            } catch (Exception e) {
                if (first && info != null) {
                    System.out.println("failed... retry with other quality");
                    info.setUserQuality(null);
                    info.setVideoQuality(null);
                    first = false;
                } else {
                    process = false;
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    public File getLastTarget() {
        return lastTarget;
    }
}
