package jp.sourceforge.nicoro;

import static jp.sourceforge.nicoro.Log.LOG_TAG;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.text.DateFormat;
import java.util.Date;

import jp.gr.java_conf.shiseissi.commonlib.DialogFragmentEx;
import jp.gr.java_conf.shiseissi.commonlib.ViewUtil;

// TODO videoNumberとThumbInfoでなくWatchVideoを中心にした処理に変更

public class PageInfoDialogFragment extends DialogFragmentEx
implements Handler.Callback {
    private static final String KEY_TITLE = "mTitle";
    private static final String KEY_URL = "mUrl";
    private static final String KEY_VIDEO_ID = "mVideoId";
    private static final String KEY_CACHE_INFO = "mCacheInfo";

    private static final int MSG_ID_THUMBINFO_FINISHED = 1;
    private static final int MSG_ID_THUMBINFO_OCCURRED_ERROR = 2;

    private String mTitle;
    private String mUrl;
    private String mVideoId;
    private String mCacheInfo;

    private ThumbInfoCacher mThumbInfoCacher;
    private ThumbnailCacher mThumbnailCacher;
    private ReuseMatcher mMatcherVideoUrl;
    private ViewGroup mViewThumbInfo;

    private final HandlerWrapper mHandler = new HandlerWrapper(this);

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_ID_THUMBINFO_FINISHED:
                updateViewThumbInfo((ThumbInfo) msg.obj);
                break;
            case MSG_ID_THUMBINFO_OCCURRED_ERROR:
                Log.e(LOG_TAG, (String) msg.obj);
                break;
        }
        return true;
    }

    public static PageInfoDialogFragment newInstance(
            String title, String url, String videoId, String cacheInfo) {
        Bundle args = new Bundle(4);
        args.putString(KEY_TITLE, title);
        args.putString(KEY_URL, url);
        args.putString(KEY_VIDEO_ID, videoId);
        args.putString(KEY_CACHE_INFO, cacheInfo);
        PageInfoDialogFragment instance = new PageInfoDialogFragment();
        instance.setArguments(args);
        return instance;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle args = getArguments();
        if (args == null && savedInstanceState != null) {
            args = savedInstanceState.getBundle(Util.KEY_ARGUMENTS);
            setArguments(args);
        }
        mTitle = args.getString(KEY_TITLE);
        mUrl = args.getString(KEY_URL);
        mVideoId = args.getString(KEY_VIDEO_ID);
        mCacheInfo = args.getString(KEY_CACHE_INFO);

        mThumbInfoCacher = NicoroApplication.getInstance(getActivity()
            ).getThumbInfoCacher();
        mThumbnailCacher = NicoroApplication.getInstance(getActivity())
                .getThumbnailCacher();
        mMatcherVideoUrl = new ReuseMatcher(WebBrowserFragment.PATTERN_VIDEO_URL);

        setStyle(DialogFragment.STYLE_NO_TITLE, 0);
        setCancelable(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(
                R.layout.page_info_dialog, container, false);
        TextView viewTitle = ViewUtil.findViewById(view, R.id.title);
        viewTitle.setText(mTitle);
        TextView viewUrl = ViewUtil.findViewById(view, R.id.url);
        viewUrl.setText(mUrl);
        TextView viewCacheInfo = ViewUtil.findViewById(view, R.id.cache_info);
        if (mCacheInfo == null) {
            viewCacheInfo.setVisibility(View.GONE);
        } else {
            viewCacheInfo.setText(mCacheInfo);
        }
        mViewThumbInfo = ViewUtil.findViewById(view, R.id.thumb_info);
        String videoId = mVideoId;
        if (videoId == null && mUrl != null) {
            videoId = WebBrowserFragment.getVideoNumberFromUrl(mMatcherVideoUrl, mUrl);
        }
        if (videoId == null) {
            mViewThumbInfo.setVisibility(View.GONE);
        } else {
            ThumbInfo thumbInfo = mThumbInfoCacher.getThumbInfo(videoId);
            if (thumbInfo == null) {
                mThumbInfoCacher.loadThumbInfo(videoId, new CallbackMessage<ThumbInfo, String>(
                        mHandler,
                        MSG_ID_THUMBINFO_FINISHED,
                        MSG_ID_THUMBINFO_OCCURRED_ERROR));
            } else {
                updateViewThumbInfo(thumbInfo);
            }
        }
        view.findViewById(android.R.id.closeButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissSafely();
            }
        });
        return view;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        mHandler.release();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBundle(Util.KEY_ARGUMENTS, getArguments());
    }

    private void updateViewThumbInfo(ThumbInfo thumbInfo) {
        ViewGroup viewThumbInfo = mViewThumbInfo;

        ImageView viewThumbnail = ViewUtil.findViewById(viewThumbInfo,
                R.id.thumbnail);
        AsyncBitmapDrawable drawable;
        ViewGroup.LayoutParams paramsThumbnail = viewThumbnail.getLayoutParams();
        String thumbnailUrl = thumbInfo.getThumbnailUrl();
        if (thumbnailUrl == null) {
            drawable = new AsyncBitmapDrawable(null,
                    paramsThumbnail.width, paramsThumbnail.height);
        } else {
            Bitmap bitmap = mThumbnailCacher.getThumbnail(thumbnailUrl);
            if (bitmap == null) {
                drawable = new AsyncBitmapDrawable(
                        paramsThumbnail.width, paramsThumbnail.height, true);
                mThumbnailCacher.loadThumbnail(thumbnailUrl,
                        new CallbackMessage<Bitmap, Void>(
                                drawable.getHandler(), 0));
            } else {
                drawable = new AsyncBitmapDrawable(bitmap,
                        paramsThumbnail.width, paramsThumbnail.height, true);
            }
        }
        viewThumbnail.setImageDrawable(drawable);

        TextView viewCountPlay = ViewUtil.findViewById(viewThumbInfo,
                R.id.count_play);
        viewCountPlay.setText(getString(R.string.info_count_play)
                + thumbInfo.getViewCounter());

        TextView viewCountComment = ViewUtil.findViewById(viewThumbInfo,
                R.id.count_comment);
        viewCountComment.setText(getString(R.string.info_count_comment)
                + thumbInfo.getCommentNum());

        TextView viewCountMylist = ViewUtil.findViewById(viewThumbInfo,
                R.id.count_mylist);
        viewCountMylist.setText(getString(R.string.info_count_mylist)
                + thumbInfo.getMylistCounter());

        Date firstRetrieve = thumbInfo.getFirstRetrieveAsDate();
        if (firstRetrieve != null) {
            TextView viewFirstRetrieve = ViewUtil.findViewById(viewThumbInfo,
                    R.id.first_retrieve);
            DateFormat dateFormat = DateFormat.getDateTimeInstance(
                    DateFormat.LONG, DateFormat.DEFAULT);
            viewFirstRetrieve.setText(dateFormat.format(firstRetrieve)
                    + " " + getString(R.string.upload));
        }

        String length = thumbInfo.getLength();
        if (length != null) {
            TextView viewLength = ViewUtil.findViewById(viewThumbInfo,
                    R.id.length);
            viewLength.setText(length);
        }

        String movieType = thumbInfo.getMovieType();
        if (movieType != null) {
            TextView viewMovieType = ViewUtil.findViewById(viewThumbInfo,
                    R.id.movie_type);
            viewMovieType.setText(movieType);
        }

        String description = thumbInfo.getDescription();
        if (description != null) {
            TextView viewDescription = ViewUtil.findViewById(viewThumbInfo,
                    R.id.description);
            viewDescription.setText(description);
        }
    }
}