/**
 * ydd-fast
 * <p>
 * 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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 com.yiqi.oss.cloud;

import com.yiqi.common.exception.ServiceException;
import org.apache.commons.io.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 本地存储
 *
 * @author douya
 * @email sunlightcs@gmail.com
 * @date 2017-03-26 16:22
 */
public class LocalStorageService extends CloudStorageService {

    private String localUrlPrefix;  //地址前缀

    private String localPath; //储存根路径

    public LocalStorageService(CloudStorageConfig config) {
        this.config = config;
        init();
    }

    private void init() {
        localUrlPrefix = config.getLocalUrlPrefix();
        localPath = config.getLocalPath();
    }

    @Override
    public String upload(byte[] data, String path) {
        String suffix = path.substring(path.lastIndexOf("."));
        return uploadSuffix(data , suffix);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        String suffix = path.substring(path.lastIndexOf("."));
        return uploadSuffix(inputStream, suffix);
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        // 上传文件流
        String path = getPath(null, suffix);  //生成后缀
        try {
            File file = new File(localPath + "/" + path);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdir();
            }
            FileUtils.copyInputStreamToFile(inputStream , file);
        } catch (Exception e) {
            throw new ServiceException("上传文件失败，请检查配置信息");
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return localUrlPrefix + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return uploadSuffix(new ByteArrayInputStream(data), suffix);
    }

}
