/*
 * Copyright 2018 Yan Zhenjie
 *
 * 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
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.sobot.album.app.album;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Color;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sobot.album.AlbumFolder;
import com.sobot.album.R;
import com.sobot.album.api.widget.Widget;
import com.sobot.album.app.Contract;
import com.sobot.album.impl.OnCheckedClickListener;
import com.sobot.album.impl.OnItemClickListener;
import com.sobot.album.widget.divider.Api21ItemDivider;

class AlbumView extends Contract.AlbumView implements View.OnClickListener {

    private Activity mActivity;

    private RecyclerView mRecyclerView;
    private GridLayoutManager mLayoutManager;
    private AlbumAdapter mAdapter;

    private TextView mBtnPreview;//预览
//    不能更改
//    private TextView mBtnSwitchFolder;//更改路径
    private TextView mTvOK;//确定
    private TextView mTVSelect;//已选中

    private LinearLayout mLayoutLoading;
    private int selectCount;
    private String selectText,sizeText;

    public AlbumView(Activity activity, Contract.AlbumPresenter presenter) {
        super(activity, presenter);
        this.mActivity = activity;
        selectText = mActivity.getResources().getString(R.string.sobot_select_photo_num);
        sizeText = mActivity.getResources().getString(R.string.sobot_pic_siza_xiaoyu);
        this.mRecyclerView = activity.findViewById(R.id.recycler_view);

//        this.mBtnSwitchFolder = activity.findViewById(R.id.sobot_text_title);
        this.mBtnPreview = activity.findViewById(R.id.sobot_tv_preview);
        this.mTvOK = activity.findViewById(R.id.sobot_tv_add);
        this.mTVSelect = activity.findViewById(R.id.sobot_tv_select);

        this.mLayoutLoading = activity.findViewById(R.id.layout_loading);

//        this.mBtnSwitchFolder.setOnClickListener(this);
        this.mBtnPreview.setOnClickListener(this);
        this.mTvOK.setOnClickListener(this);
        this.mTVSelect.setOnClickListener(this);
    }

    @Override
    protected void onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.album_menu_album, menu);
//        mCompleteMenu = menu.findItem(R.id.album_menu_finish);
    }

    @Override
    protected void onOptionsItemSelected(MenuItem item) {
//        int itemId = item.getItemId();
//        if (itemId == R.id.album_menu_finish) {
//            getPresenter().complete();
//        }
    }

    @Override
    public void setupViews(Widget widget, int column, boolean hasCamera, int choiceMode) {
       /* SystemBar.setNavigationBarColor(mActivity, widget.getNavigationBarColor());

        int statusBarColor = widget.getStatusBarColor();
        if (widget.getUiStyle() == Widget.STYLE_LIGHT) {
            if (SystemBar.setStatusBarDarkFont(mActivity, true)) {
                SystemBar.setStatusBarColor(mActivity, statusBarColor);
            } else {
                SystemBar.setStatusBarColor(mActivity, getColor(R.color.albumColorPrimaryBlack));
            }

            mProgressBar.setColorFilter(getColor(R.color.albumLoadingDark));

            Drawable navigationIcon = getDrawable(R.drawable.album_ic_back_white);
            AlbumUtils.setDrawableTint(navigationIcon, getColor(R.color.albumIconDark));
            setHomeAsUpIndicator(navigationIcon);

            Drawable completeIcon = mCompleteMenu.getIcon();
            AlbumUtils.setDrawableTint(completeIcon, getColor(R.color.albumIconDark));
            mCompleteMenu.setIcon(completeIcon);
        } else {
            mProgressBar.setColorFilter(widget.getToolBarColor());
            SystemBar.setStatusBarColor(mActivity, statusBarColor);
            setHomeAsUpIndicator(R.drawable.album_ic_back_white);
        }
        mToolbar.setBackgroundColor(widget.getToolBarColor());
*/
        Configuration config = mActivity.getResources().getConfiguration();
        mLayoutManager = new GridLayoutManager(getContext(), column, getOrientation(config), false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        int dividerSize = getResources().getDimensionPixelSize(R.dimen.album_dp_4);
        mRecyclerView.addItemDecoration(new Api21ItemDivider(Color.TRANSPARENT, dividerSize, dividerSize));
        mAdapter = new AlbumAdapter(getContext(), hasCamera, choiceMode, widget.getMediaItemCheckSelector());
        mAdapter.setAddClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                getPresenter().clickCamera(view);
            }
        });
        mAdapter.setCheckedClickListener(new OnCheckedClickListener() {
            @Override
            public void onCheckedClick(CompoundButton button, int position) {
                getPresenter().tryCheckItem(button, position);
            }

            @Override
            public void onCheckedFail() {
                Toast toast = Toast.makeText(mActivity, sizeText, Toast.LENGTH_LONG);
                // 可以控制toast显示的位置
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 10);
                toast.show();
            }
        });
        mAdapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                getPresenter().tryPreviewItem(position);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void setLoadingDisplay(boolean display) {
        mLayoutLoading.setVisibility(display ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        int position = mLayoutManager.findFirstVisibleItemPosition();
        mLayoutManager.setOrientation(getOrientation(newConfig));
        mRecyclerView.setAdapter(mAdapter);
        mLayoutManager.scrollToPosition(position);
    }

    @RecyclerView.Orientation
    private int getOrientation(Configuration config) {
        switch (config.orientation) {
            case Configuration.ORIENTATION_PORTRAIT: {
                return LinearLayoutManager.VERTICAL;
            }
            case Configuration.ORIENTATION_LANDSCAPE: {
                return LinearLayoutManager.HORIZONTAL;
            }
            default: {
                throw new AssertionError("This should not be the case.");
            }
        }
    }

    @Override
    public void setCompleteDisplay(boolean display) {
//        mCompleteMenu.setVisible(display);
    }

    @Override
    public void bindAlbumFolder(AlbumFolder albumFolder) {
//        mBtnSwitchFolder.setText(albumFolder.getName());

        mAdapter.setAlbumFiles(albumFolder.getAlbumFiles());
        mAdapter.notifyDataSetChanged();
        mRecyclerView.scrollToPosition(0);
    }

    @Override
    public void notifyInsertItem(int position) {
        mAdapter.notifyItemInserted(position);
    }

    @Override
    public void notifyItem(int position) {
        mAdapter.notifyItemChanged(position);
    }

    @Override
    public void setCheckedCount(int count) {
        selectCount = count;
        String sCount = String.valueOf(count);
        String text = String.format(selectText,sCount);
        SpannableStringBuilder ssp = new SpannableStringBuilder(text);
        ssp.setSpan(new ForegroundColorSpan(mActivity.getResources().getColor(R.color.sobot_color)),text.indexOf(sCount),text.indexOf(sCount)+sCount.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTVSelect.setText(ssp);
        if(count == 0){
            mTvOK.setBackgroundResource(R.drawable.sobot_bg_theme_unable_4dp);
        }else {
            mTvOK.setBackgroundResource(R.drawable.sobot_bg_theme_color_4dp);
        }
    }

    @Override
    public void onClick(View v) {
        if (v == mTvOK) {
            if(selectCount>0) {
                getPresenter().complete();
            }
//        } else if (v == mBtnSwitchFolder) {
//            getPresenter().clickFolderSwitch();
        } else if (v == mBtnPreview) {
            getPresenter().tryPreviewChecked();
        }
    }
}