package com.house365.web.util;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Logger;

import org.apache.commons.lang.builder.ToStringBuilder;

import com.house365.beans.entity.BaseAttachmentRemoteUrl;
import com.house365.web.util.SpringContextUtil;
import com.house365.ws.beans.request.AttachmentRemoteUrlListRequest;
import com.house365.ws.beans.response.AttachmentRemoteUrlListResponse;
import com.house365.ws.beans.response.AttachmentRemoteUrlResponse;
import com.house365.ws.interfaces.server.IAttachmentRemoteUrlInterface;


public class FileRemoteAttribute{

    /**
     * 日志记录对象
     */
    private static final Logger LOGGER = Logger
            .getLogger(FileRemoteAttribute.class.getName());

    /**
     * 随机数
     */
    private static final Random RANDOM = new Random();

    /**
     * 读写锁
     */
    private static final ReadWriteLock READ_WRITE_LOCK = new ReentrantReadWriteLock();

    /**
     * 读锁
     */
    private static final Lock READ_LOCK = READ_WRITE_LOCK.readLock();

    /**
     * 写锁
     */
    private static final Lock WRITE_LOCK = READ_WRITE_LOCK.writeLock();

    /**
     * 远程文件服务路径服务类
     */
    private static IAttachmentRemoteUrlInterface attachmentRemoteUrlInterface = null;

    /**
     *
     * @param fileLocationAttribute
     * @throws IOException
     */

    public FileRemoteAttribute(FileLocationAttribute fileLocationAttribute)
            throws IOException {
        this.remotePath = getPath(fileLocationAttribute.getRealName());
    }

    private static final String getPath(String fileName) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd/HHmmss");
        String datePath = dateFormat.format(new Date());
        String path = datePath + "_" + RANDOM.nextLong();
        return path;
    }

    /**
     * 远程服务器ID
     */
    private int remoteServerUrlId = 1;
    /**
     * 远程相对路径
     */
    private String remotePath;

    /**
     * @return the remoteServerUrlId
     */
    public int getRemoteServerUrlId() {
        return remoteServerUrlId;
    }

    /**
     * 获取远程服务路径
     *
     * @return 远程服务路径
     */
    @SuppressWarnings("unchecked")
    public String getRemoteServerUrl() {
        // 如果正在写时，无法进入
        READ_LOCK.lock();
        if (null == attachmentRemoteUrlInterface) {
            // 需要写时，先释放读锁
            READ_LOCK.unlock();
            // 写锁上锁，不允许其他读或写
            WRITE_LOCK.lock();
            if (null == attachmentRemoteUrlInterface) {
            	attachmentRemoteUrlInterface = (IAttachmentRemoteUrlInterface)SpringContextUtil.getBean("attachmentRemoteUrlInterface");
            }
            // 写锁开锁，允许其他操作
            WRITE_LOCK.unlock();
            // 读锁上锁
            READ_LOCK.lock();
        }
        // 读锁开锁
        READ_LOCK.unlock();
        // 获取指定的
        AttachmentRemoteUrlResponse response = attachmentRemoteUrlInterface.getAttachmentRemoteUrl(this.remoteServerUrlId);
        BaseAttachmentRemoteUrl attachmentRemoteUrl = response.getAttachmentRemoteUrl();
        if (null == attachmentRemoteUrl) {
            LOGGER.warning("指定的文件服务路径ID[" + this.remoteServerUrlId + "]是个不存在的ID");
            AttachmentRemoteUrlListRequest req = new AttachmentRemoteUrlListRequest();
            AttachmentRemoteUrlListResponse rsp = attachmentRemoteUrlInterface.getAttachmentRemoteUrls(req);
            List<BaseAttachmentRemoteUrl> attachmentRemoteUrls = rsp.getObjectList();
            if (null == attachmentRemoteUrls || attachmentRemoteUrls.isEmpty()) {
                LOGGER.warning("没有配置任何有效的文件服务路径");
            } else {
                attachmentRemoteUrl = attachmentRemoteUrls.get(0);
                LOGGER.warning("指定的文件服务路径ID[" + this.remoteServerUrlId
                        + "]不存在,用ID[" + attachmentRemoteUrl.getId()
                        + "]代替");
                this.remoteServerUrlId = attachmentRemoteUrl.getId();
            }
        }
        return attachmentRemoteUrl.getRemoteServerUrl();
    }

    /**
     * @return the remotePath
     */
    public String getRemotePath() {
        return remotePath;
    }

    /**
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return new ToStringBuilder(this).append("remotePath", this.remotePath)
                .append("remoteServerUrl", this.getRemoteServerUrl())
                .append("remoteServerUrlId", this.remoteServerUrlId).toString();
    }
}
