/**
 * 用于点播整体数据保存
 * 
 * **/

package com.wasu.cs.model;

import android.text.TextUtils;

import com.wasu.authsdk.entity.PriceInfo;
import com.wasu.common.WError;
import com.wasu.module.datafetch.DataFetchException;
import com.wasu.module.datafetch.ObjectBase;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DemandProgram extends ObjectBase {

	private static final long serialVersionUID = -9017393007083105656L;

	public final static int SHOWTYPE_UNKNOWN = -1;
	public final static int SHOWTYPE_NEITHER_MOVIE_NOR_TV = 0;
	public final static int SHOWTYPE_MOVIE = 1;
	public final static int SHOWTYPE_TV_SERIES = 3;

	/** 视频类型 **/
	public final static String VIDEO_TYPE_3D = "3D";
	public final static String VIDEO_TYPE_4K = "4K";
	public final static String VIDEO_TYPE_DOLBY = "DOLBY";

	public int[] updateIndex;
	
	public final static int CAT_PROP_NORMAL = 1;
	public final static int CAT_PROP_BD = 2;
	public final static int CAT_PROP_3D = 3;
	public final static int CAT_PROP_4K = 4;
	public final static int CAT_PROP_DOLBY = 5;
	
	private String id;//ID
	private String catId;//栏目ID
    private String catName;//栏目名称
    private String catEngName;//栏目英文名称
	private String title;//标题
	private String picUrl;//封面图片地址
	private String assetType;//分类 Movie:电影 Column:资讯栏目  News:资讯新闻  Series:电视剧
	private String contentChannel; // channel
	private String description;//描述
	private String area;//发行地区
	private String director;//导演
	private String actor;//演员
	private String language;//语言
	private String year;//发行年份
	private String summary;//看点
	private int itemNum;//总集数
	private int nowItem;//更新到几集
	private String pgId;//资产虚拟包ID，virtualpackage_id简写 
	private String ppv;//资产“路径” 
	private String points;//评分
	private String cmark;//资产角标
	private int isDolby;//是否杜比，0否，1是
	private String fee;

	public String getFee() {
		return fee;
	}

	public void setFee(String fee) {
		this.fee = fee;
	}

	private int isFree;//是否免费，1是，0否
	private int module;//加密模式
	private int total;//资产上线子集集数总数
	private int page;//当前请求子集页码
	private String onlineEpisodesUrl;
	private DetailSeriesSet mDetailSeriesSet;
	/** 各种码率对应的播放集合**/
	private Map<Long,DemandPlayinfo> mPlayinfoList = new HashMap<Long,DemandPlayinfo>();
	private String recommendUrl;//详情页面的相关推荐资产接口
	private String assetTagsUrl;//请求资产子集列表地址，支持分页，参见资产标签播放接口定义
	private int catProp;//资产所在栏目属性,0-常规,1-蓝光,2-3D,3-4K,4-杜比
	
	/** 用户当前播放的集数**/
	private int curPlayIndex = 1;
	private double mPrice;//当前影片价格
	private String detailUrl;//求情本详情的url地址
    private String bgPicUrl;


	private int assetFrom;//小于91代表华数自产,91代表搜狐资产,93代表咪咕影院
	private String ottAssetId;
	private String ottCatCode;
	private String ottCatId;


	private String ottEarly; //资产详情增加聚合资产是否抢先看标识
	private String ottIsFree; // 子集信息中增加聚合抢先看资产子集是否收费标识
    private String assetFromLabel;

	private PriceInfo mPriceInfo=new PriceInfo();
    @Override
	public void createFromResponse(String response) throws DataFetchException {
		try {
			JSONObject JsonData = new JSONObject(response);
			if (JsonData.getInt("code")!=200){
				throw new DataFetchException(WError.ERROR_INVALID_DATA, JsonData.getString("message"));
			}
			JSONObject playInfoJson = JsonData.getJSONObject("data");
			JSONObject program = playInfoJson.getJSONObject("detail");
			id = program.optString("id");
			catId = program.optString("catId");
			title = program.optString("title");
			picUrl = program.optString("picUrl");
			assetType = program.optString("assetType");
			contentChannel = program.optString("contentChannel");
			description = program.optString("description");
			area = program.optString("area");
			director = program.optString("director");
			actor = program.optString("actor");
			language = program.optString("language");
			year = program.optString("year");
			summary = program.optString("summary");
			itemNum = program.optInt("itemNum");
			nowItem=program.optInt("nowItem");
			pgId = program.optString("pgId");
			ppv = program.optString("ppv");
			isDolby = program.optInt("isDolby");
			module = program.optInt("module");
			total = program.optInt("total");
			page = program.optInt("page");
			points=program.optString("points");
			catName=program.optString("catName");
			catEngName=program.optString("catEngName");
			cmark=program.optString("cmark");
			isFree=program.optInt("isFree");
			fee=program.optString("fee");

            bgPicUrl = program.optString("bgPicUrl");

			assetFrom = program.optInt("assetFrom");
			ottAssetId = program.optString("ottAssetId");
			ottCatCode = program.optString("ottCatCode");
			ottCatId = program.optString("ottCatId");
			ottEarly = program.optString("ottEarly");
			ottIsFree = program.optString("ottIsFree");
			assetFromLabel = program.optString("assetFromLabel");

			//码率和播放串等item信息
            JSONArray array = playInfoJson.optJSONArray("tags");
            if (array == null) {
                throw new DataFetchException(WError.ERROR_INVALID_DATA, "播放地址不存在");
            }
			for (int i = 0; i < array.length(); i++) {
				DemandPlayinfo demandPlayinfo=new DemandPlayinfo(array.optJSONObject(i));
				mPlayinfoList.put(demandPlayinfo.getRate(),demandPlayinfo);
			}
			recommendUrl=playInfoJson.optString("recommendUrl","");
			onlineEpisodesUrl=playInfoJson.optString("onlineEpisodesUrl","");
			assetTagsUrl=playInfoJson.optString("assetTagsUrl","");
			catProp = playInfoJson.optInt("catProp", CAT_PROP_NORMAL);
			
			mPriceInfo.mOriginalPrice=-1;
			mPriceInfo.mPrice=-1;
			
		}catch (JSONException e) {
			e.printStackTrace();
            throw new DataFetchException(WError.ERROR_INVALID_DATA, "详情页数据错误");
		}
	}
    public DetailSeriesSet getDetailSeriesSet(){
    	if(mDetailSeriesSet==null||mDetailSeriesSet.getSize()==0){
    		return null;
    	}
    	return mDetailSeriesSet;
    }
    public void setDetailSeriesSet(DetailSeriesSet mDetailSeriesSet){
    	this.mDetailSeriesSet=mDetailSeriesSet;
    }

    /**
     * 获取总集数
     * @return
     */
	public int getSeriesCount() {
		if(mDetailSeriesSet == null){
			if (getAssetType() == SHOWTYPE_TV_SERIES) {
				return 0;
			} else {
				return 1;
			}
		}
		return mDetailSeriesSet.getSize();
	}

    /**
     * 获取下一集的集数
     * @return
     */
    public int getNextSeries() {
        if(mDetailSeriesSet == null){
            if (getAssetType() == SHOWTYPE_TV_SERIES) {
                return 0;
            } else {
                return 1;
            }
        }

        List<Integer> seresList = mDetailSeriesSet.getSerieslist();
        int count = seresList.size();
        if (count == 0) {
            if (getAssetType() == SHOWTYPE_TV_SERIES) {
                return 0;
            } else {
                return 1;
            }
        } else {
            int index = 0;
            for (int i = 0; i < count; i++) {
                if (curPlayIndex == seresList.get(i)) {
                    index = i;
                    break;
                }
            }

            return seresList.get(index + 1 == count ? index : index + 1);
        }
    }

    /**
     * 获取最后一集集数
     * @return
     */
    public int getLastSeries() {
        if(mDetailSeriesSet == null){
            if (getAssetType() == SHOWTYPE_TV_SERIES) {
                return 0;
            } else {
                return 1;
            }
        }

        List<Integer> seresList = mDetailSeriesSet.getSerieslist();
        int count = seresList.size();
        if (count == 0) {
            if (getAssetType() == SHOWTYPE_TV_SERIES) {
                return 0;
            } else {
                return 1;
            }
        } else {
            return seresList.get(count - 1);
        }
    }

    public String getOnlineEpisodesUrl(){
    	return onlineEpisodesUrl;
    }
    public void setPriceInfo(PriceInfo info){
    	this.mPriceInfo=info;
    }
    public PriceInfo getPriceInfo(){
    	return mPriceInfo;
    }
	public String getDetailUrl(){
		return detailUrl;
	}
	public void setDetailUrl(String detailurl){
		this.detailUrl=detailurl;
	}
	public String getPoints(){
		return points;
	}
	public String getCmark(){
		return cmark;
	}
	public String getCatName(){
		return catName;
	}
	public String getCatEngName(){
		return catEngName;
	}
	public int getIsFree(){
		return isFree;
	}
	public String getId() {
		return id;
	}
	public String getCatId() {
		return catId;
	}
	public String getTitle() {
		return title;
	}
	public String getPicUrl() {
		return picUrl;
	}
	public String getAssetTypeText(){
		return assetType;
	}
	public int getAssetType() {
		/**Movie:电影 Column:资讯栏目  News:资讯新闻  Series:电视剧  **/
		if(TextUtils.isEmpty(assetType)){
			return SHOWTYPE_UNKNOWN;
		}
		if(assetType.equalsIgnoreCase("Movie")){
			return SHOWTYPE_MOVIE;
		}else if(assetType.equalsIgnoreCase("Series")){
			return SHOWTYPE_TV_SERIES;
		}else if(assetType.equalsIgnoreCase("News")){
			return SHOWTYPE_NEITHER_MOVIE_NOR_TV;
		}else if(assetType.equalsIgnoreCase("Column")){
			return SHOWTYPE_NEITHER_MOVIE_NOR_TV;
		}
		return SHOWTYPE_UNKNOWN;
	}
	public String getDescription() {
		return description;
	}
	public String getArea() {
		return area;
	}
	public String getDirector() {
		return director;
	}
	public String getActor() {
		return actor;
	}
	public String picLanguage() {
		return language;
	}
	public String getYear() {
		return year;
	}
	public String getSummary() {
		return summary;
	}
	public int getItemNum() {
		return itemNum;
	}
	public int getNowItem() {
		return nowItem;
	}
	public String getPgId() {
		return pgId;
	}
	public String getPpv() {
		return ppv;
	}
	public int getIsDolby() {
		return isDolby;
	}
	public int getModule() {
		return module;
	}
	public int getTotal() {
		return total;
	}
	public int getPage() {
		return page;
	}
	public String getAssetTagsUrl(){
		return assetTagsUrl;
	}
	public String getRecommendUrl(){
		return recommendUrl;
	}

	public int getAssetFrom() {
		return assetFrom;
	}

	public String getOttAssetId() {
		return ottAssetId;
	}

	public String getOttCatCode() {
		return ottCatCode;
	}

	public String getOttCatId() {
		return ottCatId;
	}

    public String getAssetFromLabel() {
        return assetFromLabel;
    }

	public String getOttEarly() {
		return ottEarly;
	}

	public String getOttIsFree() {
		return ottIsFree;
	}
    /**获取更新集数最多的播放信息，用在详情页的选集UI显示**/
	public DemandPlayinfo getMaxPlayinfo(){
		if(mPlayinfoList.size()>0){
			Iterator<Long> iterator= mPlayinfoList.keySet().iterator();
			DemandPlayinfo playinfo=null;
			int len=0;
			while(iterator.hasNext()){
				DemandPlayinfo tempplayinfo;
				int templen=0;
				tempplayinfo= mPlayinfoList.get(iterator.next());
				templen=tempplayinfo.getSeriesList().size();
				if(templen>len){
					playinfo=tempplayinfo;
				}
			}
			return playinfo;
		}else{
			return null;
		}
	}
	/**获取第一个码率的播放信息，用在详情页的选集UI显示**/
	public DemandPlayinfo getFirstPlayinfo(){
		if(mPlayinfoList.size()>0){
			Iterator<Long> iterator= mPlayinfoList.keySet().iterator();
			if(iterator.hasNext()){
				return mPlayinfoList.get(iterator.next());
			}
			return null;
		}else{
			return null;
		}
	}
	/**根据码率获取对应的播放信息**/
	public DemandPlayinfo getPlayInfo(long key) {
		return mPlayinfoList.get(key);
	}
	public Map<Long, DemandPlayinfo> getmPlayinfoList() {
		return mPlayinfoList;
	}
	public void setmPlayinfoList(Map<Long, DemandPlayinfo> mPlayinfoList) {
		this.mPlayinfoList = mPlayinfoList;
	}


	/**设置选择播放的集数**/
	/*public void setCurEpisode(int episode) {
		this.curPlayIndex=episode;
	}
	public int getCurEpisode() {
		return curPlayIndex;
	}*/
	/**设置选择播放的集数**/
	public void setCurPlayIndex(int index) {
		this.curPlayIndex=index;
	}
	public int getCurPlayIndex() {
		return curPlayIndex;
	}
    /**返回所有码率的播放信息，包括播放串等**/
	public Map<Long,DemandPlayinfo> getPlayinfoList() {
		return mPlayinfoList;
	}
	/**设置影片的价格**/
	public void setPrice(double price){
		mPrice = price;
	}
	public double getPrice() {
		return mPrice;
	}

    public String getBgPicUrl() {
        return bgPicUrl;
    }

    public void addPlaySeriesInfo(DemandProgram demandProgram){
    	Set<Long> keys=mPlayinfoList.keySet();
    	for(Long key:keys){
			DemandPlayinfo playinfo = demandProgram.getPlayInfo(key);
			if (playinfo != null) {
				mPlayinfoList.get(key).getSeriesList().addAll(playinfo.getSeriesList());
			}
    	}
    }
	public boolean isNewUpdate(int string) {
		Set<Long> keys=mPlayinfoList.keySet();
    	for(Long key:keys){
    		ArrayList<DemandSeries > demandSerieslist=mPlayinfoList.get(key).getSeriesList();
    		for(DemandSeries demandSeries:demandSerieslist){
    			if(demandSeries.getEpisode() == string){
    				if(demandSeries.getIsTodayUpdate()==1){
    					return true;
    				}else{
    					return false;
    				}
    			}
    		}
    	}
		return false;
	}
	
	public int getCatProp() {
		return catProp;
	}
	
	public void setCatProp(int catProp) {
		this.catProp = catProp;
	}
	
	public void copyProperties(DemandProgram from) {
		if (from == null) {
			return;
		}
		
		id = from.id;
		catId = from.catId;
		catName = from.catName;
		catEngName = from.catEngName;
		title = from.title;
		picUrl = from.picUrl;
		assetType = from.assetType;
		contentChannel = from.getContentChannel();
		description = from.description;
		area = from.area;
		director = from.director;
		actor = from.actor;
		language = from.language;
		year = from.year;
		summary = from.summary;
		itemNum = from.itemNum;
		nowItem = from.nowItem;
		pgId = from.pgId;
		ppv = from.ppv;
		points = from.points;
		cmark = from.cmark;
		isDolby = from.isDolby;
		isFree = from.isFree;
		module = from.module;
		total = from.total;
		page = from.page;

		recommendUrl = from.recommendUrl;
		assetTagsUrl = from.assetTagsUrl;
		catProp = from.catProp;

		curPlayIndex = from.curPlayIndex;
		mPrice = from.mPrice;
		detailUrl = from.detailUrl;
		bgPicUrl = from.bgPicUrl;

		mPlayinfoList.clear();
		mPlayinfoList.putAll(from.mPlayinfoList);
	}

    public int getMinEpisode() {
        int ret = Integer.MAX_VALUE;

        Iterator<Map.Entry<Long, DemandPlayinfo>> it = mPlayinfoList.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Long, DemandPlayinfo> entry = it.next();
            DemandPlayinfo playinfo = entry.getValue();

            if (playinfo == null) {
                continue;
            }

            ArrayList<DemandSeries> seriesList = playinfo.getSeriesList();
            for (DemandSeries series : seriesList) {
                if (series.getEpisode() < ret) {
                    ret = series.getEpisode();
                }
            }
        }

        return ret;
    }

    public int getMaxEpisode() {
        int ret = 0;

        Iterator<Map.Entry<Long, DemandPlayinfo>> it = mPlayinfoList.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Long, DemandPlayinfo> entry = it.next();
            DemandPlayinfo playinfo = entry.getValue();

            if (playinfo == null) {
                continue;
            }

            ArrayList<DemandSeries> seriesList = playinfo.getSeriesList();
            for (DemandSeries series : seriesList) {
                if (series.getEpisode() > ret) {
                    ret = series.getEpisode();
                }
            }
        }

        return ret;
    }
	public boolean isFree() {
		if(mPriceInfo.mPrice<=0||mPriceInfo.mOriginalPrice<=0){
			return true;
		}
		return false;
	}
	public boolean isSinglePay() {
		if(mPriceInfo.mOriginalPrice>0&&mPriceInfo.mOriginalPrice!=99999&&mPriceInfo.mPrice>0){
			return true;
		}
		return false;
	}
	public boolean isMonthPay() {
		if(mPriceInfo.mOriginalPrice==99999&&mPriceInfo.mPrice>0){
			return true;
		}
		return false;
	}

	public String getContentChannel() {
		return contentChannel;
	}

	public void setContentChannel(String contentChannel) {
		this.contentChannel = contentChannel;
	}
}
