package com.docus.server.common.download;

import com.docus.core.util.SpringUtils;
import com.docus.server.common.download.downLoader.HttpDownloader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;


public class DownloadManager {

    private static Logger logger = LoggerFactory.getLogger(DownloadManager.class);

    enum ProtocolType {HTTP, HTTPS, FTP, BASE64, SMB, OTHER}

    ;

    public static void feedLinks(Collection<RemoteLocalPair> list, int maxHttpRetry) {
        for (RemoteLocalPair pair : list) {
            ProtocolType deal = getLinkProtocol(pair.remoteUrl);
            if (deal == ProtocolType.HTTP || deal == ProtocolType.HTTPS) {
                HttpDownload(pair, maxHttpRetry);
            } else if (deal == ProtocolType.FTP) {
            } else if (deal == ProtocolType.BASE64) {
            } else if (deal == ProtocolType.SMB) {
            } else {
                logger.error(pair.remoteUrl + " Url is not http or ftp!");
            }
        }
    }


    public static void HttpDownload(RemoteLocalPair pair, int maxHttpRetry) {
        //GeneralDownloadInfo info = new GeneralDownloadInfo(pair);
        NoCheckPointInfo info = new NoCheckPointInfo(pair);
        HttpDownloader downloader = new HttpDownloader(info, maxHttpRetry);
        downloader.intiCallBack(SpringUtils.getBean(IDownCallBack.class));
        //可以用thread.start()不过不建议
        downloader.run();
    }


    protected static ProtocolType getLinkProtocol(String link) {
        int idx = link.indexOf("://");
        if (idx == -1) {
            if (link.contains("base64")) {
                return ProtocolType.BASE64;
            }
            return ProtocolType.OTHER;
        }
        String name = link.substring(0, idx);
        if (name.equals("http")) {
            return ProtocolType.HTTP;
        }
        if (name.equals("https")) {
            return ProtocolType.HTTPS;
        }
        if (name.equals("ftp")) {
            return ProtocolType.FTP;
        }
        if (name.equals("smb")) {
            return ProtocolType.SMB;
        }
        return ProtocolType.OTHER;
    }
}
